Check if a file can be opened using portable C

I would like to quickly check if a file can be opened. It must be written in portable C, or at least to work with Win32 and POSIX systems. #ifdefs are acceptable.

I am trying to avoid this:

int openable(const char*filename) {
    FILE *f = fopen(filename,"r");
    if (!f)
        return 0; /* openable */
    fclose(f);
    return 1; /* not openable */
}

From what I can tell, stat () in its simplest form can be used to check for the presence of a file, but not to check if it is really open.

+2
source share
3 answers

The standard POSIX solution access(), which also resides in the Windows Runtime as _access().

I think this is much better than fopen()+ fclose(), because:

  • This is a well-known standard solution to the file testing problem for permissions.
  • , , ,

, , . , , , - , . "" EOF, . I/O .

+3

, , , "", .

, . , , "" , , , . .

+1

, , , , , ( , ). , : , - , , ..

, .

, , , - , , , (-, , , ). , , , - ( ).

, 'true' , , .

+1

All Articles