October 8, 2012
C How to check if a file exists
When create a program related with IO, we want to check if a file exists or not. C/C++ have a function needed to check if a file exists or not. We can use some of function in stat.h to check if a file exists. This is a simple C How to check if a file exists.
#include <stdio.h> #include <stdbool.h> #include <sys/stat.h> bool FileExists(const char* filename) { struct stat info; int ret = -1; //get the file attributes ret = stat(filename, &info); if(ret == 0) { //stat() is able to get the file attributes, //so the file obviously exists return true; } else { //stat() is not able to get the file attributes, //so the file obviously does not exist or //more capabilities is required return false; } } int main(int argc, char **argv) { bool is_file_exist; is_file_exist = FileExists(argv[1]); if(is_file_exist) printf("file %s EXIST \n", argv[1]); else printf("file %s NOT EXIST \n", argv[1]); return(1); }
Save this C How to check if a file exists code with name c_check_file.c
We can compile this C How to check if a file exists with command :
gcc c_check_file.c -o c_check_file
Call this binary C How to check if a file exists with command :
./c_check_file your_file_checked
This is a simple C How to check if a file exists. If you have other method, please share to us.
Source :http://www.developer.nokia.com/Community/Wiki/Checking_if_a_file_exists_in_Open_C_and_C%2B%2B