tags:

views:

173

answers:

4

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

+3  A: 

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.

Jerry Coffin
no if you use an fstream, you can write neither ios::out nor ios::in and you'll still be able to write and read from the file..so isn't it always the same writing of not writing ios::out ?
Ala ABUDEEB
@I.m.engineer:I'd have to check to be sure, but if memory serves an fstream is opened for both input and output by default, but if you specify ios::out, it's opened only for output, and if you specify ios::in, it's opened only for input. That's going from memory though, to it's definitely not guaranteed.
Jerry Coffin
+1  A: 

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.

RC
+1  A: 

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.

David Thornley
where to find this standard??
Ala ABUDEEB
A: 

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!

Ala ABUDEEB