Home > Net >  How to append to a std::fstream after you got to the end (std::fstream::eof() is true)
How to append to a std::fstream after you got to the end (std::fstream::eof() is true)

Time:04-27

I open a file like this (Because it's part of an exercise and it may require overwriting the file):

#include <fstream>            //std::fstream.
std::fstream file("file.txt", std::ios::in | std::ios::out);

And let's say I have read a file until the end (To get to the end of the file).

std::string tmp_buff;
while(std::getline(file, tmp_buff)) {}
file.seekp(file.tellg());

Now I have got to the end of the stream, How do I append to the file from here. Because if I just try to write like regularly, it will fail (It will not actually write):

file << "Text";

The only solution I have found is to reopen the file at the end of the file:

if(file.eof())
    {
        file.close();
        file.open("file.txt", std::ios::in | std::ios::out | std::ios::app);
        file << '\n';
    }

Any help would be appreciated.

CodePudding user response:

First, there is no need to state std::ios::in and std::ios::out when using a fstream because they are there the default value in the constructor. (it is actually std::ios_base::in/out to be more exact. std::ios (std::basic_ios<char>) inherits from std::ios_base)
So std::fstream file(filename) works the same.

The problem here is how C streams work.
When the file is read completely, the eofbit is set. After that, another reading happens which will trigger the failbit because there is nothing to read and the stream's bool conversion operator returns false and it exits the loop.

The bits will stay on until they are cleared. And while they are on, the stream doesn't do anything.
So to clear them:

file.clear();

Will do the work. You can use the stream after that.

  • Related