filesystems – Whats the best way to check if a file exists in C?

filesystems – Whats the best way to check if a file exists in C?

Look up the access() function, found in unistd.h. You can replace your function with

if( access( fname, F_OK ) == 0 ) {
    // file exists
} else {
    // file doesnt exist

You can also use R_OK, W_OK, and X_OK in place of F_OK to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK)

Update: Note that on Windows, you cant use W_OK to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK ) may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.

Use stat like this:

#include <sys/stat.h>   // stat
#include <stdbool.h>    // bool type

bool file_exists (char *filename) {
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);

and call it like this:

#include <stdio.h>      // printf

int main(int ac, char **av) {
    if (ac != 2)
        return 1;

    if (file_exists(av[1]))
        printf(%s existsn, av[1]);
        printf(%s does not existn, av[1]);

    return 0;

filesystems – Whats the best way to check if a file exists in C?

Usually when you want to check if a file exists, its because you want to create that file if it doesnt. Graeme Perrows answer is good if you dont want to create that file, but its vulnerable to a race condition if you do: another process could create the file in between you checking if it exists, and you actually opening it to write to it. (Dont laugh… this could have bad security implications if the file created was a symlink!)

If you want to check for existence and create the file if it doesnt exist, atomically so that there are no race conditions, then use this:

#include <fcntl.h>
#include <errno.h>

fd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
  /* failure */
  if (errno == EEXIST) {
    /* the file already existed */
} else {
  /* now you can use the file */

Leave a Reply

Your email address will not be published.