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
        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!
Hive OS Rig Password Security x
Hive OS Rig Password Security

Leave a Comment

Sign up to our newsletter!

ADB Commands Android Android Applications Android Build system Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development, Debugging and Performance Tools Development and Build Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia NDK / Middleware / HAL Operating System Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web Design and Development Website Hosting Wordpress Yocto Embedded Linux