Home » Programming Languages » C Programs » Check if a File Exists in C

Check if a File Exists in C

If we want to see whether certain file exists or not before doing some operation like read/write etc, then C provides an API called “access”. access() checks whether the calling process can access the file pathname.

The declaration of “access” API looks as below,

 int access(const char *pathname, int mode); 

To check if a file is present or not, we need to use mode as “F_OK”.

The below program, passes an argument of filename with absolute path, OR check a default file “adb” is present or not.

 $ vim check_if_file_present.c 
#include <stdio.h> // for printf
#include <stdlib.h> // for malloc
#include <string.h> // for strcpy
#include <unistd.h> // for access
 
int main(int argc, char **argv) {
        int result;
        //allocate memory of 512 bytes
        char *filename = (char *)malloc(512);
        if (argc < 2) {
                strcpy(filename, "/usr/bin/adb");
        } else {
                strcpy(filename, argv[1]);
        }
        result = access (filename, F_OK); // F_OK tests existence also (R_OK,W_OK,X_OK).
                                  //            for readable, writeable, executable
        if ( result == 0 ) {
                printf("%s exists!!\n",filename);
        } else {
                printf("ERROR: %s doesn't exist!\n",filename);
        }
        //free allocated memory
        free(filename);
        return 0;
}
 $ gcc -o check_if_file_present check_if_file_present.c 

$ ./check_if_file_present check_if_file_present.c

$ ./check_if_file_present check_if_file_present.c 
check_if_file_present.c is present!! 

Let’s now check if we have a file “test_file.pdf”

$ ./check_if_file_present test_file.pdf
ERROR: test_file.pdf doesn't exist!

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment