How do I detect the reason for an stream fail state?

I'm taking Intro to Programming. Today we learned about using fstream to read/write to the filesystem. The teacher mentioned "fail states", saying they can happen for a variety of reasons, including the file not existing.

Let's say I have a program where a fail state happens. Obviously, if a fail state happens, the program should act appropriately, but first it must know why the fail state happened.

For now, let's please keep it C++11.
One good thing to do is -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}


And basically only read the file all is good.

Might not be exactly what you're looking for though.

http://www.cplusplus.com/doc/tutorial/files/
http://www.cplusplus.com/reference/ios/ios/fail/
Last edited on
Stream failure can happen for a lot of reasons, but C++ isn't interested in most of them, only that something went wrong.

No matter what stream, or how it is opened, you should test its state after every read attempt. If any kind of failure occurs, you can test what that specific class of error is, either by querying the iostate directly or using one of the accessor functions like bad() and fail().

See http://en.cppreference.com/w/cpp/io/ios_base/iostate

If you want to know more than that, you have to know something about the stream's source and the operating system.

Hope this helps.
Topic archived. No new replies allowed.