Open In App

std::ifstream::is_open() in C++

Last Updated : 22 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The std::ifstream::is_open() function in C++ is a member function of the std::ifstream class, which is used to check if a file stream object has successfully opened a file for reading or not. This function returns a boolean value, true if the file stream is open and ready for I/O operations, and false otherwise.

In this article, we will learn the std::ifstream::is_open() function, its syntax, how it works, and provide practical example to demonstrate its use in C++ file handling.

Syntax of std::ifstream::is_open() in C++

fileStream.is_open();

Here, fileStream is an object of the std::ifstream class.

Parameters of std::ifstream::is_open()

The std::ifstream::is_open() function does not take any parameters.

Return Value of std::ifstream::is_open()

The return value of the std::ifstream::is_open() function indicates whether the file stream is open or not.

  • It returns true if the file is successfully opened.
  • It returns false if the file stream has not successfully opened a file

Example of std::ifstream::is_open() in C++

The example below demonstrates how to use std::ifstream::is_open() in C++ to check if a file was successfully opened. After attempting to open a file with std::ifstream, we use is_open() to verify the success of the operation. Depending on the result, we can proceed with file operations or handle any errors.

C++
// C++ program to use std::ifstream::is_open() in C++ to check if a file was successfully opened.
#include <fstream>
#include <iostream>
using namespace std;

int main(){
  
    // Attempt to open the file "example.txt" for reading
    ifstream file("example.txt");

    // Check if the file was successfully opened
    if (file.is_open()) {
        cout << "File opened successfully!" << endl;
        // Perform file operations here (e.g., reading from the file)
    }
    else {
        cout << "Failed to open file." << endl;
    }

    // Close the file to release resources
    file.close();

    return 0; 
}


Output

File opened successfully!

Time Complexity: O(1) as std::ifstream::is_open() simply checks the state of the file stream.
Auxiliary Space: O(1), as it does not require any additional memory allocation.


Next Article
Practice Tags :

Similar Reads