I’d like to perform a quick check whether or not a file can be opened. It should be written in portable C, or at least to work on Win32 and POSIX systems. #ifdefs are acceptable.
I’m 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 if file exists, but not to check if it’s actually openable.
The POSIX standard solution is
access(), which is also in the Windows runtime as_access().I guess it is slighly better than
fopen()+fclose()because:Of course, it is just as susceptible to race conditions as any other way of doing such a test. In a way, the only safe way to know if a file is availble for reading is to open it and try to read, without closing it in between. Even then, you still need to watch for ‘unexpected’ EOF, of course. I/O is hard.