Search code examples
c++iostream

Why does ofstream work here, but not fstream?


I am trying to understand a difference between std::ofstream and std::fstream. I have this code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
    string line;
    //create an output stream to write to the file
    //append the new lines to the end of the file
    ofstream myfileI ("input.txt", ios::app);
    
    
    if (myfileI.is_open())
    {

        myfileI << "\nI am adding a line.\n";
        cout << myfileI.fail() << "\n";
        myfileI << "I am adding another line.\n";
        cout << myfileI.fail() << "\n";

        myfileI.close();
    }
    else cout << "Unable to open file for writing";

The fail bits return 0, so it is writing.

But the fail bits return 1 when I use the exact same code but instead use fstream instead of ofstream.

input.txt is just this:

Read and write to this file. 

What am I doing here?

This is not a good example of a file

Solution

  • I see no practical difference between the two cases you describe.

    The ONLY technical difference is that ofstream always has the ios::out flag enabled, which will be added to any flags you specify. Whereas fstream has the ios::in and ios::out flags enabled by default, but will be overriden by any flags you specify.

    So, in the ofstream case you are opening the file in ios::out | ios::app mode, whereas in the fstream case you are opening the file in just ios::app mode.

    But, both streams delegate to std::filebuf, and according to this reference for std::filebuf::open(), both out|app and app modes act the exact same way - as if fopen(filename, "a") were used, thus they will both "Append to file" if the file exists, and "Create new" if the file does not exist.

    image