The best way to check if a file exists using standard C/C++

In C programming, checking if a file exists is a common task that can be accomplished by attempting to open the file for reading. If the file opens successfully, it exists; otherwise, it doesn't exist.

Syntax

FILE *fopen(const char *filename, const char *mode);

Method 1: Using fopen() Function

The most straightforward approach is to use fopen() to attempt opening the file in read mode −

#include <stdio.h>

int main() {
    FILE *file;
    
    /* Try to open file for reading */
    file = fopen("sample.txt", "r");
    
    if (file != NULL) {
        fclose(file);
        printf("File exists\n");
    } else {
        printf("File doesn't exist\n");
    }
    
    return 0;
}
File doesn't exist

Method 2: Using access() Function

Another approach is using the access() function to check file accessibility −

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

int main() {
    const char *filename = "test.txt";
    
    /* Check if file exists using access() */
    if (access(filename, F_OK) == 0) {
        printf("File '%s' exists\n", filename);
    } else {
        printf("File '%s' doesn't exist\n", filename);
    }
    
    return 0;
}
File 'test.txt' doesn't exist

Method 3: Function-Based Approach

Creating a reusable function to check file existence −

#include <stdio.h>

int fileExists(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (file) {
        fclose(file);
        return 1;  /* File exists */
    }
    return 0;  /* File doesn't exist */
}

int main() {
    const char *file1 = "existing.txt";
    const char *file2 = "nonexistent.txt";
    
    printf("Checking file: %s - %s\n", file1, 
           fileExists(file1) ? "Exists" : "Doesn't exist");
    printf("Checking file: %s - %s\n", file2, 
           fileExists(file2) ? "Exists" : "Doesn't exist");
    
    return 0;
}
Checking file: existing.txt - Doesn't exist
Checking file: nonexistent.txt - Doesn't exist

Comparison of Methods

Method Function Used Portability Best For
fopen() fopen() Standard C Basic file existence check
access() access() POSIX systems Checking specific permissions
Function wrapper fopen() wrapper Standard C Reusable code

Key Points

  • Always close the file using fclose() after successful fopen()
  • Check for NULL return value to determine if file opening failed
  • access() is POSIX-specific and may not work on all systems

Conclusion

The fopen() method is the most portable way to check file existence in standard C. It works across all platforms and provides reliable results for basic file existence checking.

Updated on: 2026-03-15T10:44:35+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements