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

时间:2012-03-02 06:30:00

标签: c++ text-files

我需要一些关于删除txt文件中最后一个字符的帮助。例如,如果我的txt文件包含1234567,我需要C ++代码删除最后一个字符,以便该文件变为123456.谢谢大家。

4 个答案:

答案 0 :(得分:5)

在可移植代码中执行此操作的唯一方法是读入数据,并写出除最后一个字符之外的所有字符。

如果您不介意非可移植代码,大多数系统都提供截断文件的方法。传统的Unix方法是寻找你希望文件结束的地方,然后在那一点写一个0字节到文件。在Windows上,您可以使用SetEndOfFile。其他系统将使用不同的名称和/或方法,但几乎所有系统都具有某种形式的能力。

答案 1 :(得分:4)

对于便携式解决方案,这些内容应该可以胜任:

#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;
}

答案 2 :(得分:2)

这是一个更强大的方法,关闭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在this post的第一个解决方案的启发。它应该是那里最快的解决方案。

答案 3 :(得分:1)

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

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.

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

相关问题