I'm trying to check the status of my file i/o stream in an if statement using the fail() function and I get a build error. I've tried to sift through the reference articles here but I'm terribly confused on the topic of flags. Can anyone help me?
(I'm using Codeblocks)
reference to ios_base is ambiguous
candidates are class ios_base
class std::ios_base
'ios_base' does not name a type
'fail' was not declared in this scope
Hi class ios_base;/// tremove this you are attempting to redefine a library class]
if(fail() == true) what stream are checking here ?
1 2 3 4 5 6 7 8 9 10
//if ifile is a file stream
ifstream ifile ("data.txt");
///check like this
if (ifile. fail ()){//do something}
///even simpler
if (! ifile)//better
///evaluate on read
while (ifile)//get data from file
If a stream in ok then a goodbit is set on that stream meaning you can use that stream
To read
If a stream runs into an error you cant use that stream
We always check to see if an error state have been set on a stream
Three error states can be set
1. Failbit - this set when a stream runs into a resolvable eg read the wrong data type for example
1 2 3 4 5
int val; cin>> val ; /// suppose you key in char 'z' to val a Failbit will be set on that stream
///and the following reads will fail , you might experience a scenario similar to an infinite loop
/// this error state can be cleared by using clear () that each stream have
cin.clear (); stream can then be used again
2. eofbit- this error state is set when a stream strikes the end-of-file character
3. badbit- this is set when the stream reads corrupt data this stream can't be reused again
By default the goodbit state is always set if stream is ok
while (!ifile)///is a Boolean expression it checks if any of the error state is sey
///note all those States apply to iostreams filestreams and stringstreams
Ley say you have a text file in which there are multiple friend names per line, you can use the loop to read all names while no error state is set om the stream
1 2 3 4 5 6 7 8 9 10
ifstream ifile ("names.txt");
if(! ifile){cout <<"file not found"; exit (1);}// if goodbit isn't set because the file wasn't found exit;
string name;
while (ifile)///otherwise while goodbit is on read names
{
getline (ifile, name,'\n');
cout <<name <<endl;
}