How to Get Error Message When ifstream Open Fails in C++?
Last Updated :
06 Feb, 2024
In C++, the std::ifstream class is used to open a file for input operations. It associates an input stream to the file. However, due to some reasons, it may be unable to open the requested file. In this article, we will learn how to show an error message when the ifstream class fails to open the file.
Get Error Message When ifstream Open Fails in C++
Determining the cause of an operation failure when opening a file using ifstream is to know what we need to do to rectify the error. Generally, the causes of this failure consist of:
- File Not Found: There is no file with the provided name in the given directory.
- Problems with Permissions: The application may not be authorized to read the file.
- File in Use: The file cannot be accessed for reading because another process is utilizing it.
- Inadequate Resources: Not enough resources may be available to open the file.
The std::ifstream is inherited from the std::ios_base class and this class has two flags namely: std::ios::badbit and std::ios::failbit which are set when the errors occur. We can check if they are set using std::ios::bad() and std::ios::fail() functions.
In addition, the errorno is set after the system call failure (which in this case is open()) and we can use the strerror( ) to get a textual representation of the error.
C++ Program to Show Error Message When ifstream Fails
C++
#include <cstring>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream file;
const char * filename = "example.txt" ;
file.open(filename);
if (!file.is_open()) {
cerr << "Error opening file: " << filename
<< std::endl;
if (file.bad()) {
cerr << "Fatal error: badbit is set." << endl;
}
if (file.fail()) {
cerr << "Error details: " << strerror ( errno )
<< endl;
}
return 1;
}
file.close();
return 0;
}
|
Output
Error opening file: example.txt
Error details: No such file or directory
Share your thoughts in the comments
Please Login to comment...