Read a file char by char - C++ File Stream

C++ examples for File Stream:Text File

Description

Read a file char by char

Demo Code

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()/*from   w  ww  . jav a 2s. c  o m*/
{
   string filename = "test.dat";
   char ch;
   long offset, last;
   ifstream inFile(filename.c_str());
   if (inFile.fail())   // check for successful open
   {
      cout << "\nThe file was not successfully opened\n Please check that the file currently exists" << endl;
      exit(1);
   }
   inFile.seekg(0L,ios::end);
   last = inFile.tellg();
   for (offset = 1L; offset <= last; offset++)
   {
      inFile.seekg(-offset,ios::end);
      ch = inFile.get();
      cout << ch << " : ";
   }
   inFile.close();
   cout << endl;
   return 0;
}

Result


Related Tutorials