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.
The default mode for std::fstream
s is std::ios::in|std::ios::out
. (Source)
The reason your code doesn't print anything to test1.txt
is that the std::ios::in|std::ios::out
mode does not create the file if it does not already exist (Source: table on this page).
You can use the std::ios::in|std::ios::app
mode, which will start reading from the start, will start writing from the end, and will create the file if it does not exist. Note that using app
mode, the file will seek to the end before each write (Source).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With