1

I have a simple C++ file read program:

int main() {
    std::string buf;
    std::ifstream file;
    file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    try {
        file.open("C:\\Test11.txt");
        char c;
        while (!(file.eof())) {
            file.get(c);
            std::cout << c;         
        }
    }
    catch (std::ifstream::failure e) {
        std::cout << e.what() << std::endl;
        std::cout << e.code() << std::endl;
        std::cout << "Exception opening/reading file";
    }
    file.close();
    return 0;
}

The content of file at C:\Test11.txt is Hello.

The program is able to read the content but fails with exception ios_base::failbit. It seems to have problem while evaluating while (!(file.eof())).

What is going wrong?

Biffen
  • 5,354
  • 5
  • 27
  • 32
Abhinav
  • 1,665
  • 2
  • 19
  • 24
  • http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Biffen Mar 29 '16 at 14:48
  • @Biffen: Thanks! I understand the problem now, but I can't find a way out. As after reading only we will encounter the EOF and at the same place the exception happens. Am I missing something? – Abhinav Mar 29 '16 at 15:12
  • What exact behaviour do you want? – Ulrich Eckhardt Mar 29 '16 at 15:20
  • @UlrichEckhardt: 1) We want to read the file and display it on console. 2) In case of any error ie. a) file doesn't exist b) read issue due to disk problem we want to catch the exception and show "Exception opening/reading file" – Abhinav Mar 29 '16 at 15:24
  • You can use the file in a boolean expression to check if it was opened successfully. You can stream the address of a streambuffer into another stream to copy data between two streams. You can eventually check if the stream reached EOF to distinguish between success and failure. – Ulrich Eckhardt Mar 29 '16 at 15:29
  • @UlrichEckhardt: I didn't get the second part. The problem, I am facing is file,get(c) throws exception as soon as EoF is encountered and I can not get to know about EoF before that. – Abhinav Mar 29 '16 at 16:04
  • Concerning the second part above, check out overload #9 at http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt. Concerning the failure to reach EOF, simply don't tell the stream to throw exceptions if either bit is set. – Ulrich Eckhardt Mar 29 '16 at 17:59
  • @UlrichEckhardt: You mean that instead `file.exceptions(std::ifstream::failbit | std::ifstream::badbit);`. I should use `file.exceptions(std::ifstream::failbit);`. If yes, then when to use std::ifstream::badbit and std::ifstream::eofbit ? – Abhinav Mar 30 '16 at 11:05

0 Answers0