Fairly self explanatory, how do I check to see if a file exists before I write to it in C.
1 Answer
A favorite is access:
/* test that file exists (1 success, 0 otherwise) */ int xfile_exists (char *f) { /* if access return is not -1 file exists */ if (access (f, F_OK ) != -1 ) return 1; return 0; } Note: access() is defined by POSIX, not C, so its availability will vary from compiler to compiler.
2 Comments
Jonathan Leffler
And said favourite has problems — see the comments to the duplicate, where the accepted answer also uses
access() but arguably shouldn't.David C. Rankin
Thanks. Primarily working on a single OS, the availability issue often slips consideration. I dropped a note regarding its availability and definition.
O_EXCLmode along withO_CREAT. This is an atomic test; there is no TOCTOU (Time of Check, Time of Use) window of vulnerability. Generally, it is better to use 'Easier to Ask Forgiveness than Permission' (EAFP) rather than 'Look Before You Leap' (LBYL) testing.open(), you can usually achieve the effect you require. If you need a file stream, usefdopen()to create one from the open file descriptor.O_CREATandO_EXCLflags (and check for anEEXISTerror) to avoid race conditions.