How to check if a file exists before creating it

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

+4
source share
1 answer

You cannot do it reliably. Meanwhile, when you check if a file exists, and when you create it, another process can create it.

You just have to go and create a file. Depending on what you are trying to do, you may need one of these options for what to do if the file already exists:

  • edit previous contents in place: open("file", O_RDWR|O_CREAT, 0666)
  • delete previous contents: open("file", O_WRONLY|O_CREAT|O_TRUNC, 0666 )
  • add to previous content: open("file", O_WRONLY|O_CREAT|O_APPEND, 0666)
  • operation failed: open("file", O_WRONLY|O_CREAT|O_EXCL, 0666)

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

In addition, 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 this is to write the new contents to a new file, and then use rename to move it over the old file .

+16
source

Source: https://habr.com/ru/post/911686/


All Articles