C File Exists

Summary: in this tutorial, you will learn how to develop a C file exists function that checks whether a file exists using various C built-in standard I/O functions.

C File ExistsSometimes you want to check if a file exists before doing anything else such as backup, copy, modify or just read data from the file. However, C does not provide any built-in function to check if a file exists.

Fortunately, we can use other built-in functions to develop our own function check whether a file exists. There are several ways to accomplish this task.

C file exists function using fopen() function

In the first approach, we will try to read the data from the file using the fopen() function. If we can read data from the file, it means the file exists otherwise it does not. The following is the C file exists function to check if a file exists using the fopen() function.

The function accepts file name and return 1 if the file exists, otherwise it returns 0.

C file exists checking function using stat() function

In the second approach, instead of reading data from a file, we read the file’s attributes using the stat() function. The stat() function return zero (0) if the operation is successful, otherwise if file does not exist, it returns -1.

We can make use of the stat() function to check if a file exists as follows:

Testing C file exists checking function

Let’s test our C file exist checking function. First you need to create a file in the C:\temp directory called test.txt or whatever name you like. Then you can use the following code snippet to test the function:

In this tutorial, you have learned how to use standard C functions to develop a C file exists checking functions that check if a file exists.