Check file read status - C++ File Stream

C++ examples for File Stream:File Operation

Description

Check file read status

Demo Code

#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
   char ch;/*from   ww  w  .j ava 2s. c o m*/

   ifstream fin("main.cpp");

   if(!fin) {
      cout << "Cannot open file.\n";
      return 1;
   }
   do {
      // Read the next character, if there is one.
      fin.get(ch);
      // Check for an error NOT caused by reaching EOF.
      if(!fin.eof() && (fin.fail() || fin.bad())) {
         cout << "Input Error\n";
         fin.close();
         return 1;
      }
      // If EOF not yet encountered, display the next character.
      if(!fin.eof()) cout << ch;
   } while(!fin.eof());

   fin.clear();

   fin.close();

   if(!fin.good()) {
      cout << "Error closing file.";
      return 1;
   }
   return 0;
}

Result


Related Tutorials