C++ ifstream Open a file in read mode and exception handling.
#include <iostream> #include <fstream> #include <cstdlib> // needed for exit() #include <string> using namespace std; int main()//from www . j a v a2s .co 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); } }