open automatically file for writing fails

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream inOutFile;
    inOutFile.open("students.dat", ios::out| ios::in | ios::binary);
    if (!inOutFile)
	cout<< "error";
    return 0;
}


my question is, why the file is created automatically only if you'll remove ios::in?
Last edited on
Because the default open mode for an output stream (ofstream) creates the file, or if the file exists it deletes the contents. The default mode for an input stream (ifstream) will fail if the file doesn't exist.

For an fstream() you need to add the trunc or app option to force the file to be created if it doesn't exist. But note that trunc deletes the file content and with app all writing is done at the end of the file.

But beware of the failure modes when using the wrong flags together.

For C++98
If the mode has both trunc and app set, the opening operation fails. It also fails if either is set but out is not, or if both app and in are set.

For C++11
If the mode has both trunc and app set, the opening operation fails. It also fails if trunc is set but out is not.


Unless you specifically need both read and write functionality on the same stream you may want to consider using separate streams for input and output.
Thanks a lot, helpful!
Topic archived. No new replies allowed.