Fairly self explanatory, how do I check to see if a file exists before I write to it in C.
Asked
Active
Viewed 174 times
0
-
3Open it with read mode and check if it is successful – Rizier123 Dec 23 '14 at 00:21
-
If you've got POSIX and you're simply trying to ensure that you don't clobber an existing file when you open it for writing, include the `O_EXCL` mode along with `O_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)](http://stackoverflow.com/questions/404795/lbyl-vs-eafp-in-java/405220#405220) testing. – Jonathan Leffler Dec 23 '14 at 00:32
-
With the options available with POSIX [`open()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html), you can usually achieve the effect you require. If you need a file stream, use [`fdopen()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fdopen.html) to create one from the open file descriptor. – Jonathan Leffler Dec 23 '14 at 00:33
-
1How to check if the file exists before writing to it? DON'T. There's no guarantee that something else won't create the file after you've checked but before you write. Instead, open the file with `O_CREAT` and `O_EXCL` flags (and check for an `EEXIST` error) to avoid race conditions. – Brendan Dec 23 '14 at 03:50
1 Answers
0
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.

David C. Rankin
- 81,885
- 6
- 58
- 85
-
1And said favourite has problems — see the comments to the duplicate, where the accepted answer also uses `access()` but arguably shouldn't. – Jonathan Leffler Dec 23 '14 at 00:29
-
Thanks. Primarily working on a single OS, the availability issue often slips consideration. I dropped a note regarding its availability and definition. – David C. Rankin Dec 23 '14 at 01:00