Use eof() to read and display a text file. : File End EOF « File « C++






Use eof() to read and display a text file.

  
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
  char ch;

  ifstream fin("text.txt");

  if(!fin) {
    cout << "Cannot open file.\n";
    return 1;
  }

  do {
    fin.get(ch);

    if(!fin.eof() && (fin.fail() || fin.bad())) {
      cout << "Input Error\n";
      fin.close();
      return 1;
    }
    if(!fin.eof()) cout << ch;
  } while(!fin.eof());

  fin.clear();
  fin.close();

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

  return 0;
}
  
    
  








Related examples in the same category

1.While it is not the end of a file, output file line by line
2.ios::ate places the get-position pointer at the file end, enable tellg() to return the size of the file