Example 1:
//model for error
detection
//using header <assert.h>
#include <fstream.h>
#include <assert.h>
int main(void)
{
.
. .
ofstream fout;
.
. .
fout.open("myFile");
assert (!
fout.fail( ));
<send data to file>
fout.close( );
assert (!
fout.fail( )):
.
. .
}
|
When using <assert.h>, if a problem with the
file occurs, the error message
will be:
Assertion failed....
Abnormal program termination.
In Example 1, the stream operation
mode was not included.
|
|
Example 2:
//model for
error detection using
//build your own error trap
#include <fstream.h>
int main(void)
{
int num;
ofstream.fout;
fout.open("myFile";ios::out);
if (fout)
{
for(int i =
0; i < 10; i++)
{
cin>>num:
fout<<num<<endl;
}
}
else
{
cout<<"file not
found.";
}
fout.close( );
return 0;
}
|
fout will be 0 (false) if an error exists.
In Example 2, the stream operation mode WAS included.
The file was formed using endl to
organize the data in the file.
|
|