0

Fairly self explanatory, how do I check to see if a file exists before I write to it in C.

4
  • 3
    Open it with read mode and check if it is successful Commented Dec 23, 2014 at 0: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) testing. Commented Dec 23, 2014 at 0:32
  • With the options available with POSIX open(), you can usually achieve the effect you require. If you need a file stream, use fdopen() to create one from the open file descriptor. Commented Dec 23, 2014 at 0:33
  • 1
    How 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. Commented Dec 23, 2014 at 3:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And said favourite has problems — see the comments to the duplicate, where the accepted answer also uses access() but arguably shouldn't.
Thanks. Primarily working on a single OS, the availability issue often slips consideration. I dropped a note regarding its availability and definition.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.