boolean expression in file output

it is on the use of boolean expression to control the output to file, and this is the code:
1
2
3
4
5
6
7
8
9
10
11
12
bool fileStatus;
...............
...............
ofstream fout(fileName);

fileStatus=fout;

cout<<fileStatus<<endl;
fout<<"information provided by user"<<endl;
fout<<name<<"\n";
fout<<age<<" "<<height<<" "<<weight<<endl;
fout.close();


and the result in the output file does not show the fileStatus thing( cout<<fileStatus<<endl;) and the textbook says this is used as a control to output files. The fout is obviously a class, how can we assign it to the boolean variable? Would anybody please explain how the boolean expression work(control the output to the file)? Thanks!
im a little confused by your question. Are you trying to see if the file opened successfully with the boolean expression so you can begin writing to it?
The fout is obviously a class, how can we assign it to the boolean variable?

ofstream has an operator void* (inherited from its ios base class)
http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/

And the compiler knows how to treat pointers like booleans, to support code like if (ptr) { ...

so

fileStatus=fout;

is actually

fileStatus=(bool)(void*)fout;

which is the equivalent to

fileStatus=(0 != (void*)fout);

where operator void* is defined along the line of (this is from the Visual C++ xiosbase header)

1
2
3
4
	operator void *() const
		{	// test if any stream operation has failed
		return (fail() ? 0 : (void *)this);
		}


so you could use

fileStatus=!fout.fail();

instead.

Andy
Last edited on
Thanks for your clear, neat and thoroughly explanation! I really learn a lot from it. I am sorry I did not make the second question clear. Please see below:

cout<<fileStatus<<endl;


If the fileStatus is 0, will it stop immediately? I mean the
fout<<"information provided by user"<<endl;
fout<<name<<"\n";
fout<<age<<" "<<height<<" "<<weight<<endl;
fout.close();
will not be executed.

In other word, What is the function of the
cout<<fileStatus<<endl;

It seems a little weird to me because it tries to cout a boolean value.

Thanks Andy and Slider!
As coded, all the calls to insert into fout will still be made, but fail. You need to use an if()

1
2
3
4
5
6
7
8
9
10
11
ofstream fout(fileName);

bool fileStatus=fout;

cout<<fileStatus<<endl;
if (fileStatus) {
    fout<<"information provided by user"<<endl;
    fout<<name<<"\n"; 
    fout<<age<<" "<<height<<" "<<weight<<endl;
    fout.close();
}


though you'd normally omit the temp bool variable.
Last edited on
Yes, thanks for explanation. It makes more sense to me now. Thanks for your kindly help!
Topic archived. No new replies allowed.