Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a 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; } 
like image 310
Dave Marshall Avatar asked Oct 23 '08 14:10

Dave Marshall


People also ask

How do I check if a file exists in C?

access() Function to Check if a File Exists in C Another way to check if the file exists is to use the access() function. The unistd. h header file has a function access to check if the file exists or not. We can use R_OK for reading permission, W_OK for write permission and X_OK to execute permission.

How do you determine whether a file exists?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .

How do you check if a file is in a directory in C?

The isDir() function is used to check a given file is a directory or not.

Which function is used to check file existence?

The file_exists() function checks whether a file or directory exists.


2 Answers

Look up the access() function, found in unistd.h. You can replace your function with

if( access( fname, F_OK ) == 0 ) {     // file exists } else {     // file doesn't exist } 

You can also use R_OK, W_OK, and X_OK in place of F_OK to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK)

Update: Note that on Windows, you can't use W_OK to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK ) may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.

like image 67
Graeme Perrow Avatar answered Oct 22 '22 04:10

Graeme Perrow


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; } 
like image 32
codebunny Avatar answered Oct 22 '22 04:10

codebunny