How to check if file exists using stat
Problem:
You want to use stat()
from sys/stat.h
POSIX header to check if a file with a given name exists.
Solution
Use this function:
#include <sys/stat.h>
/**
* Check if a file exists
* @return true if and only if the file exists, false else
*/
bool fileExists(const char* file) {
struct stat buf;
return (stat(file, &buf) == 0);
}
If you want to use C++ std::string
for the filename, you can use this equivalent instead:
#include <sys/stat.h>
/**
* Check if a file exists
* @return true if and only if the file exists, false else
*/
bool fileExists(const std::string& file) {
struct stat buf;
return (stat(file.c_str(), &buf) == 0);
}
Note that these function to not check if the file is a normal file. They just check if something (a normal file, a UNIX domain socket, a FIFO, a device file etc.) with the given name exists
For a detailed stat()
reference, see the Opengroup page on stat
If you don’t know for a fact if stat() exists in your environment, you can use the std::ifstream
method described here instead