if i opened a file like:
ofstream file("file.dat",ios::binary);
or
ofstream file("file.dat",ios::binary | ios::out);
what can i do with a file opened in the latter form that i can't do with the former form and vice versa
thank you
if i opened a file like:
ofstream file("file.dat",ios::binary);
or
ofstream file("file.dat",ios::binary | ios::out);
what can i do with a file opened in the latter form that i can't do with the former form and vice versa
thank you
For an ofstream, ios::out
is the default, so there's no difference. I believe the only time specifying ios::out makes a difference is if you use an fstream, which can be opened for reading or writing, or both.
In most cases I would expect there to be no difference, though it seems like this could technically be implementation specific.
In my implementation (gcc 3.4.3) the open for the ofstream uses the ios:::out mode in the ofstream->open() call regardless of what is specified via the constructor so it's purely optional. If using fstream, this is not the case and would need to be specified explicitly.
Checking out the Standard, section 27.8.1.3 discusses the various ios
modifiers (like ios::in
and ios::out
), and maps them to the C fopen()
parameters. According to the Standard, if there are no modifiers specified on a file open, the open fails.
In 27.8.1.9, we find that ofstream
works like that, but with ios::out
automatically specified. Therefore, the answer to the original question is that both will work exactly the same.
I don't know why people are finding that opening with an fstream
without either ios::in
or ios::out
, but my reading of the Standard says it shouldn't work. I'd be interested in other people's readings of 27.8.1.3.
thanks for all people who answered me: i now tested several codes depending on what i have been answered and came up with this summary:
using ofstream: ios::out is the default even if nothing is specified, but if you used only ios::in with ofstream, no compilation errors (unless you use read() or >> or some ifstream object) but no files would be written.
using ifstream: ios::in is the default even if nothing is specified, but if you used only ios::out with ifstream, no compilation errors (unless you use write() or << or some ofstream object) but you can't read any information from the file.
using fstream: no defaults, you have to explicitly determine what you are going to do. Otherwise, no compilation error but you don't get what you want simply.
as for the original question , both work exactly the same!