C++ delete last character in a txt file

拈花ヽ惹草 提交于 2019-12-01 08:18:34

The only way to do this in portable code is to read in the data, and write out all but the last character.

If you don't mind non-portable code, most systems provide ways to truncate a file. The traditional Unix method is to seek to the place you want the file to end, and then do a write of 0 bytes to the file at that point. On Windows, you can use SetEndOfFile. Other systems will use different names and/or methods, but nearly all will have the capability in some form.

Alex Z

For a portable solution, something along these lines should do the job:

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

Here's a more robust method, going off Alex Z's answer:

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

The trick is these lines, which allow you to read the entire file efficiently into the string, and not just a token:

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

This is inspired from Jerry Coffin's first solution in this post. It is supposed to be the fastest solution there.

vaisakh

If the input file is not too large, you can do the following:-

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.

If the file is too large, you can possibly use a temporary file instead of a character array. It will be a bit slow though.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!