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.
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:
open("file", O_RDWR|O_CREAT, 0666)
open("file", O_WRONLY|O_CREAT|O_TRUNC, 0666
)open("file", O_WRONLY|O_CREAT|O_APPEND, 0666)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With