C program to check whether a file or directory exists or not

Write a C program to check whether a file or directory exists or not. How to check file or directory exists or not in C programming. What is the best way to check file or directory exists or not in C programming.

Required knowledge

Basic Input Output, File handling

How to check if file exists or not?

Unlike other modern programming languages like Java or C#, C does not have any direct built-in library function to check file or directory existence. However, still there are various ways to check if a file exists or not.

C supports three ways to check existence of a file on disk. I will explain them one by one.

  1. Using fopen() function

    We have used fopen() function several times through the course of file handling exercises. fopen() returns pointer to FILE type on success otherwise NULL.

    You can use fopen() function to open given file in read mode. If it returns NULL then file does not exists otherwise exists on disk.

    Testing file existence using fopen() is not reliable. fopen() fails if you don't have read/write/execute permissions on file. In such case also fopen() returns NULL, but file exists.

  2. Using access() function

    int access(const char *path, int amode); function is defined in unistd.h header file. It is used to check accessibility of a file. It is more reliable to check file existence.

    It accepts two parameters, first *path is a pointer to constant character pointing to file path. Next is amode which is a bit pattern defined by one or combination of F_OK, R_OK, W_OK and X_OK constants.

    It returns 0 if file has requested access amode, otherwise -1.

  3. Using stat() function

    Probably this is not the best way to check file existence. But if you have stat structure object then you can also use it for checking file existence or check other file permissions.

    st_mode field of stat structure contains bit pattern specifying permissions on file. If F_OK bit is set on st_mode field then file exists otherwise not.

Program to check whether a file exists or not

/**
 * C program to check whether a file exists or not.
 */

#include <stdio.h>
#include <unistd.h>
#include <io.h>
#include <sys/stat.h>

int isFileExists(const char *path);
int isFileExistsAccess(const char *path);
int isFileExistsStats(const char *path);


int main()
{
    char path[100];

    printf("Enter source file path: ");
    scanf("%s", path);


    // Check if file exists or not
    if (isFileExistsAccess(path))
    {
        printf("File exists at path '%s'\n", path);
    }
    else
    {
        printf("File does not exists at path '%s'\n", path);
    }

    return 0;
}



/**
 * Function to check whether a file exists or not.
 * It returns 1 if file exists at given path otherwise
 * returns 0.
 */
int isFileExists(const char *path)
{
    // Try to open file
    FILE *fptr = fopen(path, "r");

    // If file does not exists 
    if (fptr == NULL)
        return 0;

    // File exists hence close file and return true.
    fclose(fptr);

    return 1;
}



/**
 * Function to check whether a file exists or not using 
 * access() function. It returns 1 if file exists at 
 * given path otherwise returns 0.
 */
int isFileExistsAccess(const char *path)
{
    // Check for file existence
    if (access(path, F_OK) == -1)
        return 0;

    return 1;
}



/**
 * Function to check whether a file exists or not using
 * stat() function. It returns 1 if file exists at 
 * given path otherwise returns 0.
 */
int isFileExistsStats(const char *path)
{
    struct stat stats;

    stat(path, &stats);

    // Check for file existence
    if (stats.st_mode & F_OK)
        return 1;

    return 0;
}

In the above program I have defined functions to check file existence using all three methods described above. However, I haven't used them all, you can use any of the above defined methods.

Output

Enter source file path: data/file3.txt
File exists at path 'data/file3.txt'

How to check if directory exists or not?

To check directory existence we will again use stat structure. sys/stat.h header file defines a macro S_ISDIR(), used to check directory existence. The macro accepts stat.st_mode param and returns a non-zero integer if given file is a directory, otherwise zero.

Program to check directory existence

/**
 * C program to check whether a directory exists or not.
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>

int isDirectoryExists(const char *path);


int main()
{
    char path[100];

    printf("Enter directory path: ");
    scanf("%s", path);


    // Check if directory exists or not
    if (isDirectoryExists(path))
    {
        printf("Directory exists at path '%s'\n", path);
    }
    else
    {
        printf("Directory does not exists at path '%s'\n", path);
    }

    return 0;
}



/**
 * Function to check whether a directory exists or not.
 * It returns 1 if given path is directory and  exists 
 * otherwise returns 0.
 */
int isDirectoryExists(const char *path)
{
    struct stat stats;

    stat(path, &stats);

    // Check for file existence
    if (S_ISDIR(stats.st_mode))
        return 1;

    return 0;
}

Output

Enter directory path: data
Directory exists at path 'data'

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>