How to Check File Existence in Standard C++
There are numerous methods to find out if a file is there, such as the following:
1: How to Check File Existence in C++ Using stat() function
The stat() method is the most efficient and secure technique to verify file existence. The sys/stat.h header file has a predefined function called stat. The function accepts a path and a structure as parameters, where the file or directory associated metadata, if any, would be kept. The function returns the result of 0 if the route is a legitimate one. We would check for the existence of the file as an example:
#include <sys/stat.h>
using namespace std;
int main()
{
const char* FILE = "C_File.txt";
struct stat sb;
if (stat(FILE, &sb) == 0)
cout << "This file exists";
else
cout << "The file does not exists!";
return 0;
}
First, the FILE pointer variable stores the file’s path. After that, the stat header file’s format is used to initialize the empty structure. Metadata would be saved in this way. The stat function is then called inside of the if condition. The result would be 0 if the path is correct, meaning the file or directory existed; otherwise, it would be non-zero.
Output
Note: Ensure replacing the filename “C_File.txt” with the file name you want to check.
2: How to Check File Existence in C++ Using std::ifstream() function
Using the C++ standard library function std::ifstream is another method to determine whether a file is present. A stream object that may be used to read the file is returned by this function, which accepts a path as an input. To use this function, the developer would pass the path and name of the file to the constructor of the std::ifstream class. The result of doing this is either the file being successfully opened by the constructor, or an exception being thrown. As a result, if the file is opened, the developer can assume that it is present.
#include <fstream>
using namespace std;
int main(){
ifstream file("file_name.txt");
if (file.good())
{
std::cout << "file exists." << endl;
}
else
{
std::cout << "file doesn't exist." << endl;
}
}
Starting with the main() method, an object of the ifstream class named file is created to read the target file later. When invoking the open function on the file object, the destination file name is then supplied as an argument. This line will attempt to open the file in read-only mode.
Since a file may only be opened if it physically exists there and cannot be accessed otherwise. We are indirectly utilizing the open() method to verify the file’s existence. Then, using if-else conditional statements, we determine if the file object has opened the file or not; if it has, this means that it is located on the specified path, and we display a success message; otherwise, we produce an error message.
Output
3: How to Check File Existence in C++ Using fopen() function
The third way to check if a file exists is to use the C++ function fopen(). The fopen() method creates a stream and opens the file indicated by filename. The mode variable is a character string that indicates the kind of file access that has been requested. One positional parameter precedes optional keyword arguments in the mode variable.
We can save the return value from the execution of fopen() in the pointer file when it has finished. If the file opening was successful, the function fopen(), which shows if the file had previously opened, will produce a file stream pointer referring to the target file. If it was unsuccessful, which indicates if the file had already been, it will return NULL. Then, if the file reference is not NULL, we know the file is present and may produce a success message; otherwise, an error message will be sent.
#include <fstream>
using namespace std;
int main()
{
FILE* file;
file = fopen("C_File.txt", "r");
if (file!=NULL)
{
cout << "File exists" << endl;
}
else
{
cout << "File does not exists" << endl;
}
return 0;
}
To read the file, we build a pointer to the FILE class starting from the main () method. Next, we use the arguments “C_File.txt” and “r” to define the target file and the action we want to perform on it when we execute the fopen () method. ‘r’ indicates that we want to read the file.
Output
Conclusion
There are different C++ functions to check if a file exists, which are stat, std::ifstream and fopen. Of the three methods, stat() function is the quickest and most reliable way to check file existences. While other two functions are also useful for checking the file existence. Therefore, developers should consider using these functions for optimal performance and reliability when checking for file existence.