Course contentsShow
← C
Lesson 762 of 1,21910. Input and OutputFree lesson

Checking if a file exists

Checking if a file exists

What you'll learn: How to use the access() function to verify a file's presence before your program tries to open it.

The "Knock Before Entering" Rule

Imagine you are a delivery driver. Before you try to shove a large package through a mail slot, you probably want to check if the house actually exists or if the front door is blocked. In C, trying to open a file that isn't there can cause your program to crash or behave unpredictably.

While you could simply try to open a file and check if it returns NULL, there is a more specialized tool for "peeking" at a file without actually touching its contents: the access() function.

Using the access() Function

The access() function lives in the <unistd.h> library. It asks the operating system, "Does this file exist, and do I have permission to use it?"

To check for a file's existence, we use a special constant called F_OK (short for File OK).

#include <stdio.h>
#include <unistd.h>

int main() {
    char *filename = "config.txt";

    // access() returns 0 if the condition is met
    if (access(filename, F_OK) == 0) {
        printf("The file exists! Proceeding to open...\n");
    } else {
        printf("Error: The file %s could not be found.\n", filename);
    }

    return 0;
}

How it Works

The function takes two arguments: the path to the file and the mode of check. When you use F_OK, the function returns 0 if the file is found. If it returns -1, it means the file is missing or the path is incorrect.

Think of access() as a lightweight sensor. Opening a file with fopen() is a "heavy" operation—it allocates memory and sets up a data stream. Checking for existence first is a "light" operation that saves time and prevents errors, especially when dealing with system-level tasks or temporary files that might have been deleted by another process.

Why Not Just Use fopen()?

Checking for existence separately is helpful when you want to prevent overwriting an important file. For example, if your program creates a temporary log, you might check if temp_log.txt already exists. If it does, you can stop and ask the user for permission to overwrite it, rather than blindly deleting what was already there.

Key takeaway

Use access(filename, F_OK) to quickly check for a file's existence without the overhead of opening it.