C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Check whether file exists

C Program: Check whether file exists

C

#include <stdio.h>

 

int main() {

    FILE *file;

    char filename[100];

 

    // Step 1: Ask user for filename

    printf("Enter file name: ");

    scanf("%s", filename);

 

    // Step 2: Try opening the file in read mode

    file = fopen(filename, "r");

 

    // Step 3: Check if file pointer is NULL

    if (file == NULL) {

        printf("File '%s' does not exist.\n", filename);

    } else {

        printf("File '%s' exists.\n", filename);

        fclose(file); // Always close if opened successfully

    }

 

    return 0;

}

Output

 
Case 1: File Exists 
Enter file name: data.txt
File 'data.txt' exists.

Case 2: File Does Not Exist
Enter file name: notes.txt
File 'notes.txt' does not exist.

Explanation

Step

Description

1

Prompts user to input the filename.

2

Attempts to open the file in "r" mode (read).

3

If fopen() returns NULL, the file does not exist.

4

Otherwise, the file exists — so close it using fclose().