In this article, we are going to learn different ways of how to check if File Exists in C Language in a directory or not.We will learn different methods in C language to detect the presence of a file.
1. How to check if File Exists in C Language using open()
In this first c program example, we are making use of the fopen() function to check if the file exists or not. We are trying to open the file, if the file open fails then we can say the file does not exist. To run this program, we need one text file with the name Readme.txt in the same folder where we have our code.
The content of the file is:
Hello My name is
John
danny
C Program check if a File Exists
#include<stdio.h>
int main(void)
{
FILE *file;
if (file = fopen("Readme.txt", "r"))
{
fclose(file);
printf("The file you are trying to open is available.");
}
else
{
printf("The file you are trying to open is not available.");
}
return 0;
}
Output:
The file you are trying to open is available.
Most Popular Post
- How to Read text File word by word in C
- How to Read File Line by Line in C
- How to count words in a text file in C
- How to count words in a text file in C
- How to get File Size timestamp access status in C
2. How to check if File Exists in C Language using stat()
In this example, we are going to detect the presence of the file with the help of stat() function. We will try to read the file attribute information by using the stat() function, if this function fails then we can say the files do not exist. Let us understand this with the help of the below code. To run this program , we need one text file with name Readme.txt in the same folder where we have our code.
C Program to check if a File Exists
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
const char *filename = "Readme.txt";
int main(int argc, char *argv[])
{
struct stat sb;
if (stat(filename, &sb) == -1)
{
printf("The file you are looking for is not available.");
}
else
{
printf("The file you are looking for is available.");
}
return 0;
}
Output
The file you are looking for is available
3,How to check if File Exists in C Language using access()
In this example, we are going to make use of the access() function to judge the presence of a file in a directory.We need to include unistd.h header file in our program to make use of the access() function.
C Program to check if a File Exists
#include<stdio.h>
#include<unistd.h>
const char *filename = "Readme.txt";
int main(int argc, char *argv[])
{
if (access(filename, F_OK) != -1)
{
printf("The file you are looking for is available.");
}
else
{
printf("The file you are looking for is not available.");
}
return 0;
}
Output:
The file you are looking for is available.
Summary
In this post we have learned how to check if a File Exists in C Language with examples by using different function that are using open(),using stat(),using access()