Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 715
Rajesh Avatar asked Oct 26 '17 07:10

Rajesh


2 Answers

The default mode for std::fstreams 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).

like image 52
pizzapants184 Avatar answered Sep 21 '22 23:09

pizzapants184


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.

like image 44
MSalters Avatar answered Sep 21 '22 23:09

MSalters