C++ program to Throw an Error if FILE does not exist

// program to read content of an existing file
//if file does not exist, throw an error in catch block
//and display message "File doesn't exist...."

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
  char msg[]="File doesn't exist....";
  char ch;
  ifstream file;
  try
  {
    file.open("Deepraj.txt");
    if(file.fail())
      throw msg;
    file>>ch;
    while(file.eof()==0)
    {
      cout<<ch;
      file>>ch;
    }
  }
  catch(char str[])
  {
    cout<<str;
  }
  file.close();
  return 0;
}

No comments:

Post a Comment