Open a file in read mode and includes exception handling. - C++ File Stream

C++ examples for File Stream:File Operation

Description

Open a file in read mode and includes exception handling.

Demo Code

#include <iostream>
#include <fstream>
#include <cstdlib>  // needed for exit()
#include <string>
using namespace std;
int main()//from   ww  w .j a  v a2s .c o m
{
   string filename = "prices.dat";
   string descrip;
   double price;
   ifstream inFile;
   try
   {
      inFile.open(filename.c_str());
      if (inFile.fail()) throw filename;  // the exception being checked
         inFile >> descrip >> price;
      while (inFile.good())  // check next character
      {
         cout << descrip << ' ' << price << endl;
         inFile >> descrip >> price;
      }
      inFile.close();
      return 0;
   }
   catch(string e)
   {
      cout << e << " was not successfully opened.\n Please check that the file currently exists." << endl;
      exit(1);
   }
}

Related Tutorials