How to handle errors when opening file for reading and closing the file in C++ programming

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Opening a file for reading which if fail, error messages displayed on the standard output in C++ programming

To show: How to handle errors when opening file for reading and closing the file in C++ programming

 

// a very simple 'exception handling' when opening file for reading. There is no testfileio.txt at the root of C drive at the beginning.

#include <iostream>

#include <fstream>

using namespace std;

 

void main(void)

{

char filename[ ] = "C:\\testfileio.txt";

ifstream inputfile;

 

inputfile.open(filename, ios::in);

// test if fail to open fail for reading

if(inputfile.fail())

{

cout<<"Opening "<<filename<<" file for reading\n";

cout<<"---------------------------------------\n";

cout<<"The "<<filename<<" file could not be opened!\n";

cout<<"Possible errors:\n";

cout<<"1. The file does not exist.\n";

cout<<"2. The path was not found.\n";

exit(1); //just exit

// 0-normal, non zero - some error

}

// if successful opening file for reading

else

{

cout<<"The "<<filename<<" file was opened successfully!\n";

cout<<"\nDo some file processing here...\n";

}

inputfile.close();

// test if fail to close the file

if(inputfile.fail())

{

cout<<"\nThe file "<<filename<<" could not be closed!\n";

exit(1);

}

// else, do...

else

cout<<"\nThe "<<filename<<" file was closed successfully!\n";

}

 

Output examples:

 

Opening C:\testfileio.txt file for reading

---------------------------------------

The C:\testfileio.txt file could not be opened!

Possible errors:

1. The file does not exist.

2. The path was not found.

Press any key to continue . . .

 

Create testfileio.txt on the C drive and re-run the program. The following output should be expected.

 

The C:\testfileio.txt file was opened successfully!

Do some file processing here...

The C:\testfileio.txt file was closed successfully!

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index