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.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
iostreaminterface. There may also be a way to wrap an iostream around the file descriptor you get fromopen, 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
renameto move it over the old file.