Steffan Harris
Steffan Harris

Reputation: 9336

How to test if a file exists before creating it

I would like to see if a file exists. If it does not exists, then I would like to create it. I am using Linux by the way.

Upvotes: 5

Views: 1403

Answers (1)

zwol
zwol

Reputation: 140866

You can't do that reliably. Between when you check to see if the file exists and when you create it, another process may create it.

You should just go ahead and create the file. Depending on the larger thing you're trying to do, you might want one of these options for what to do if the file already exists:

  • modify the previous contents in place: open("file", O_RDWR|O_CREAT, 0666)
  • erase the previous contents: open("file", O_WRONLY|O_CREAT|O_TRUNC, 0666)
  • append to the previous contents: open("file", O_WRONLY|O_CREAT|O_APPEND, 0666)
  • fail the operation: open("file", O_WRONLY|O_CREAT|O_EXCL, 0666)

Most of these, but unfortunately not all, have equivalents at the higher level iostream interface. There may also be a way to wrap an iostream around the file descriptor you get from open, depending on which C++ library you have.

Also, I should mention that if you want to atomically replace the contents of a file (so no process ever sees an incomplete file) the only way to do that is to write out the new contents to a new file and then use rename to move it over the old file.

Upvotes: 17

Related Questions