
In this post we will see how to write a C++ code to check if the file exists in the file system or not.
To find if the file exists or not we will use the stat structure from sys/types.h library (#include <sys/types.h>).
The basic signature for stat is shown below.
// stat() stats the file pointed to by path and fills in buf. int stat(const char *path, struct stat *buf);
So lets See an example to check if a file exist using standard C++/C++11
C++: Check if file exists:
/** C++ Program find if file exists of not by codebind.com */ #include<iostream> #include <sys/stat.h> bool FileExists(const std::string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } int main() { std::string filename = "C:/file_name.txt"; std::cout << "Does file_name.txt Exists ? " << FileExists(filename) << std::endl; return 0; } /* OUTPUT: Does file_name.txt Exists ? 1 */
Leave a Reply