Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a file exists before creating it

Tags:

c++

file

linux

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.

like image 778
Steffan Harris Avatar asked Oct 22 '11 22:10

Steffan Harris


1 Answers

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.

like image 195
zwol Avatar answered Sep 27 '22 22:09

zwol