C++删除txt文件中的最后一个字符

C++ delete last character in a txt file

本文关键字:最后一个 字符 文件 删除 txt C++      更新时间:2023-10-16

我需要一些帮助来删除txt文件中的最后一个字符。例如,如果我的txt文件包含1234567,我需要用C++代码删除最后一个字符,使文件变成123456。谢谢大家。

在可移植代码中实现这一点的唯一方法是读入数据,并写出除最后一个字符之外的所有字符。

如果您不介意不可移植的代码,大多数系统都提供了截断文件的方法。传统的Unix方法是查找文件的结束位置,然后在该位置向文件写入0字节。在Windows上,可以使用SetEndOfFile。其他系统将使用不同的名称和/或方法,但几乎所有系统都具有某种形式的功能。

对于一个可移植的解决方案,应该采用以下方法:

#include <fstream>
int main(){
    std::ifstream fileIn( "file.txt" );              // Open for reading
    std::string contents;
    fileIn >> contents;                              // Store contents in a std::string
    fileIn.close();
    contents.pop_back();                             // Remove last character
    std::ofstream fileOut( "file.txt", std::ios::trunc ); // Open for writing (while also clearing file)
    fileOut << contents;                             // Output contents with removed character
    fileOut.close();
    return 0;
}

这里有一个更健壮的方法,根据Alex Z的答案:

#include <fstream>
#include <string>
#include <sstream>
int main(){
    std::ifstream fileIn( "file.txt" );                   // Open for reading
    std::stringstream buffer;                             // Store contents in a std::string
    buffer << fileIn.rdbuf();
    std::string contents = buffer.str();
    fileIn.close();
    contents.pop_back();                                  // Remove last character

    std::ofstream fileOut( "file.txt" , std::ios::trunc); // Open for writing (while also clearing file)
    fileOut << contents;                                  // Output contents with removed character
    fileOut.close(); 
}

诀窍在于这些行,它允许您有效地将整个文件读取到字符串中,而不仅仅是一个令牌:

    std::stringstream buffer;
    buffer << fileIn.rdbuf();
    std::string contents = buffer.str(); 

这篇文章的灵感来源于Jerry Coffin在这篇文章中提出的第一个解决方案。这被认为是最快的解决方案。

如果输入文件不是太大,可以执行以下操作:-

1. Read the contents into a character array.
2. Truncate the original file.
3. Write the character array back to the file, except the last character.

如果文件太大,可以使用临时文件而不是字符数组。不过会有点慢。