Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What's the best way to check if a file exists in C?

Is there a far better way than simply trying to open the file?

int exists(const char fname)
{
FILE
file;
if ((file = fopen(fname, "r")))
{
fclose(file);
return 1;
}
return 0;
}
by

2 Answers

akshay1995

FILE *file;
if((file = fopen("sample.txt","r"))!=NULL)
{
// file exists
fclose(file);
}
else
{
//File not found, no memory leak since 'file' == NULL
//fclose(file) would cause an error
}
kshitijrana14
Use stat like this:

#include <sys/stat.h> // stat
#include <stdbool.h> // bool type

bool file_exists (char *filename) {
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
and call it like this:

#include <stdio.h> // printf

int main(int ac, char
av) {
if (ac != 2)
return 1;

if (file_exists(av[1]))
printf("%s exists\n", av[1]);
else
printf("%s does not exist\n", av[1]);

return 0;
}

Login / Signup to Answer the Question.