How to check if file exists using C program ?

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
        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! 
Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply