Write a C Program to Check if a File Exists or Not

In this article, We will write a C program to check if a file exists or not on a given path.

The program asks the user to enter the file path, checks if the file exists or not on the specified path and prints the result on the screen.

Sample Input:

Enter the file path or name: temp.txt

Sample Output:

The given file exists.

Like other programming languages, there is no built-in function in C that we could directly use to check if a given file exists or not. However, we do have an easy way to check it.

The easiest way to check if a file exists or not in C is the fopen() function.

The fopen() function takes in the the file name or file path as the first parameter and the mode in which the file should open as a second parameter.

If the file exists on the given path, the fopen() function returns a pointer of type FILE which points to the start of the file.

But if the file does not exist on the specified path, it returns a NULL pointer.

Here is the syntax of the fopen() function:

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

Let’s put together the above steps and write a C program to check if the given file exists or not:

// C program to check if a
// file exists or not

#include<stdio.h>

int main(){
	
	char filepath[100];
	
	printf("Enter the file path or name: ");
	scanf("%s", &filepath);
	
	// Try to open the file in read mode
	FILE *fptr = fopen(filepath, "r");
	
	if(fptr!=NULL){
		
		// File exists, so print message and close it
		printf("The given file exists.");
		fclose(fptr);
	}
	else{
		printf("File does not exist.");
	}
	
    return 0;
    
}

Output:

Enter the file path or name: temp.txt
The given file exists.

Enter the file path or name: data/myfile.txt
The given file exists.

Why do we use fclose() function?

In the above program, if you pay enough attention, we have explicitly called the fclose() function after checking if the file exists. But why do we need to do that?

This is because when you open a file for reading or writing purpose using a program and do not close it, there are chances that the file might get locked and other processes or parts of your program may not be able to access or modify the file while it’s open.

Closing the file with fclose() releases any file locks, allowing other processes or parts of your program to work with the file.

There are a few other reasons also such as resource limiting, file corruption, etc. So, always make sure to close the file by calling the fclose() function at the end of your program.

I hope you liked this article. Thanks for reading!

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts