Does the File Exist?

Many programs rely upon external files to store data. When the file is missing, or not where it should be, the fopen() function returns a NULL pointer, which your code can act upon. Or, you can pre-check for the file’s existence by using the access() function.

The access() function does more than just check to see if a file is present. It can also check the file’s type and permissions. The function is prototyped in the unistd.h header file. Here is the man page format:

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

The path is the filename or the complete path to a file or directory. The mode argument determines the file’s permissions by using constant expressions and logical operations. Here are the constant expressions defined in unistd.h:

Constant Test
F_OK Does the file exist?
R_OK Does the file have read permission?
W_OK Does the file have write permission?
X_OK Does the file have execute or search permission?

When the access() function is successful, zero is returned, -1 otherwise. The errno variable is set when -1 is returned.

The following code demonstrates the access() function as a test on the existence of the file gettysburg.txt, which is assumed to be in the same directory as the program:

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

int main()
{
    const char filename[] = "gettysburg.txt";
    int r;

    r = access(filename,F_OK);
    if( r == 0 )
        printf("File '%s' exists\n",filename);
    else
        printf("File '%s' cannot be found\n",filename);

    return(0);
}

The access() function at Line 9 does not open the file. It’s just a test. Likewise, with any of the mode arguments, the file isn’t opened. Sometimes such a thing is necessary in your code. And if you use this function, ensure that you properly inform the user of a file’s condition, how it affects the program, and what the user can do to remedy the situation.

Finally, the access() function has some issues worthy of concern. For example, when checking file permissions remember that they can change as your program runs. Some permission issues can affect system security. Refer to the access() function’s man page for specific details.

Leave a Reply