c++ - fstream::exceptions unexpected behaviour -


In the code below; Any ideas why ifs gets spoiled when std :: is copied?

  #include & lt; Iostream & gt; # Include & lt; Fstream & gt; # Include & lt; Algorithm & gt; #include & lt; Iterator & gt; Int main (int argc, char * argv []) {std :: fstream ifs (argv [1], std :: fstream :: in | std :: fstream :: binary); Std :: fstream ofs (argv [2], std :: fstream :: out | std :: fstream :: trunc | std :: fstream :: binary); Ifs.unsetf (std :: ios_base :: skipws); Std :: istream_iterator & lt; Unsigned four & gt; (IFS) start; Std :: istream_iterator & lt; Unsigned four & gt; End; Std :: ostream_iterator & lt; Four & gt; Begin2 for sale (OFS); Ifs.exceptions (std :: fstream :: badbit | std :: fstream :: failbit); Ofs.exceptions (std :: fstream :: badbit | std :: fstream :: failbit); If (! Ifs) std :: cerr & lt; & Lt; "If Bad" & lt; & Lt; Std :: endl; If (! OSS) std :: cerr & lt; & Lt; "Bad of" & lt; & Lt; Std :: endl; Try {std :: copy (start, end, start 2); } Hold (...) {if (ifs.bad ()) std :: cerr & lt; & Lt; "Exception: Bad Bad" & lt; & Lt; Std :: endl; If (ifs.fail ()) std :: cerr & lt; & Lt; "Exception: IFS failed" & lt; & Lt; Std :: endl; If (ifs.eof ()) std :: cerr & lt; & Lt; "Exception: IFS AOF" & lt; & Lt; Std :: endl; } If (! Ifs) std :: cerr & lt; & Lt; "If Bad" & lt; & Lt; Std :: endl; If (! OSS) std :: cerr & lt; & Lt; "Bad of" & lt; & Lt; Std :: endl; // ofs & lt; & Lt; Ifs.rdbuf (); }   

This is the output I get.

  ~ $ cp fstream.cpp ~ / tmp / fstream / ~ $ g ++ -ggdb -O0 efstream CPP ~ $ ./a.out a.out xxx.ooo exception: ifs failed Exception: ifs eof ifs bad    

given as a place to stop duplicates (Created by default) The expiration iterator will compare the equivalent of the other etter while trying to read the specified data of the file. In this situation, it changes all the data in the file and reaches the EOF. This means that everything is successful, but the stream is now in an unsuccessful state, unless you reset it, you will not be able to do anything else with that stream.

You have even misunderstood things: ! Stream is equivalent to stream.fail () , but it not like stream.bad () . stream.bad () means that there has been a serious failure such as the hard drive being dying when you were trying to read it. stream.fail () may mean a bit (or normal) as if it is likely to fail in an attempt, possibly because you are reading some data that has not changed in the target type (For example, in the stream there is "one" and you are trying to read int ) or because (in this case) you have reached the end of the file.

Bottom line: Iostreams exceptions are rare only for very little use. Some exceptions are defined to throw in completely normal, expected cases.

Comments