Search code examples
c++iofstream

writing after reading using fstream


I am under the impression fstream objects in c++ can be used to both read and write, using the same stream. I have successfully been able to first write to a stream and then read from it. If I however try to write to it again the file is not affected.

Here is a code example that successfully compiles on windows using MinGw:

int main()
{
    std::string path="file.txt";

    std::fstream fs(path.c_str());
    int buffSize=100;
    int bytesRead=0;
    char* buffer=new char[buffSize];

    fs.write("hello", 5);
    fs.seekp(0, std::ios::beg);
    fs.read(buffer, buffSize);
    bytesRead=fs.gcount();
    for(int i=0;i<bytesRead;i++) {std::cout << buffer[i];}
    std::cout << "\n";
    fs.clear();
    fs.seekp(1, std::ios::beg);
    fs.write("E", 1);
    std::cout << "fail: " << fs.fail() << "\n";

    delete[] buffer;
}

The initial content of "file.txt" was only:

AAAAAAA

And the program outputs:

helloAA
fail: 0

Looking at the file in a text editor after running the program shows that the final content is:

helloAA

The final writing of the "E" has not taken effect, why is this and how do I fix it?

EDIT:

I tried using fs.clear() before writing again as user 0x499602D2 suggested. Also added a line printing out whether the failbit or badbit has been set or not and updated the program output. The final file content stays the same however, the problem remains.


Solution

  • (more verbose answer from what I posted in comments on the question)

    You need to call flush() on output stream objects (derived from ostream) in order for the data to actually be written on the output stream. More information on flush() is available on this c++ reference page.