File validation exists in C

I am trying to open a file in application C. How can I check if a file exists before trying to read it?

+5
source share
6 answers

Try to open it:

FILE * file;
file = fopen("file_name", "r"));
if (file){
   //file exists and can be opened 
   //...
   // close file when you're done
   fclose(file);
}else{
   //file doesn't exists or cannot be opened (es. you don't have access permission )
}
+12
source

Existence: call stat(), check for a return code that has no side effects. On UNIX, call access().

You would do this if you just did what you asked if FileA exists, not necessarily I can open it. Example. On UNIX, a file with run-only permissions does not open, but still exists.

stat st_mode . , , fopen open, , .

+6

- :

bool file_exists(const char * filename) {
    if (FILE * file = fopen(filename, "r")) {
        fclose(file);
        return true;
    }
    return false;
}

, .

+3

fopen.

FILE *fp;

if (!(fp = fopen(name, "r"))) {
    perror("fopen");
    /* Handle error, return, exit, try again etc. */
}

/* Normal code goes on. */

fopen NULL, - . , , .

+2

, , . , , , , stat. stat, , . Windows, Unix.

MSDN opengroup.

Windows

Unix

+1

You open the file and check the return value of fopen()or open().

0
source

All Articles