Open In App

How to Get Error Message When ifstream Open Fails in C++?

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. File Not Found: There is no file with the provided name in the given directory.
  2. Problems with Permissions: The application may not be authorized to read the file.
  3. File in Use: The file cannot be accessed for reading because another process is utilizing it.
  4. 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++




// C++ Program to show error message if ifstream fails to
// open a file
#include <cstring>
#include <fstream>
#include <iostream>
using namespace std;
  
int main()
{
    ifstream file;
    const char* filename = "example.txt";
  
    // Attempt to open the file
    file.open(filename);
  
    // Check if the open operation failed
    if (!file.is_open()) {
        cerr << "Error opening file: " << filename
             << std::endl;
  
        // Check for specific error conditions
        if (file.bad()) {
            cerr << "Fatal error: badbit is set." << endl;
        }
  
        if (file.fail()) {
            // Print a more detailed error message using
            // strerror
            cerr << "Error details: " << strerror(errno)
                 << endl;
        }
  
        // Handle the error or exit the program
        return 1;
    }
  
    // File opened successfully, continue processing...
  
    // Close the file when done
    file.close();
  
    return 0;
}


Output

Error opening file: example.txt
Error details: No such file or directory



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads