c++file-handlingtdm-gcc

Default mode of fstream


I was looking at the SO post C++ file stream open modes ambiguity. I wanted to know the default file opening mode of fstream. One of the answer says,

What the above implies is that the following code opens the file with exactly the same open flags fstream f("a.txt", ios_base::in | ios_base::out); ifstream g("a.txt", ios_base::out); ofstream h("a.txt", ios_base::in);

So if I understand correctly, in case I create object of fstream, I should be able to either read or write.

But below code does not write any data to file

fstream testFile1;
testFile1.open("text1.txt");
testFile1<<"Writing data to file";
testFile1.close();

However adding mode as given below creates text file with data "Writing data to file"

testFile1.open("text1.txt", ios::out);

So whether the default mode is implementation defined? I am using TDM-GCC-64 toolchain.


Solution

  • The default mode of ifstream is in. The default mode of ofstream is out. That's why they're named that way. fstream has no default mode.

    Your example only shows the two defaults, and it shows that by omission of explicit arguments. That fstream f("a.txt", ios_base::in | ios_base::out) uses two explicit arguments is precisely because there is no default mode.