I wrote a method which tries to create a file. However I set the flag CREATE_NEW so it can only create it when it doesnt exist. It looks like this:
for (;;)
  {
    handle_ = CreateFileA(filePath.c_str(), 0, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_DELETE_ON_CLOSE, NULL);
    if (handle_ != INVALID_HANDLE_VALUE)
      break;
    boost::this_thread::sleep(boost::posix_time::millisec(10));
  }
This works as it should. Now I want to port it to linux and and of course the CreateFile function are only for windows. So I am looking for something equivalent to this but on linux. I already looked at open() but I cant seem to find a flag that works like CREATE_NEW. Does anyone know a solution for this?
Take a look at the open() manpage, the combination of O_CREAT and O_EXCL is what you are looking for.
Example:
mode_t perms = S_IRWXU; // Pick appropriate permissions for the new file.
int fd = open("file", O_CREAT|O_EXCL, perms);
if (fd >= 0) {
    // File successfully created.
} else {
    // Error occurred. Examine errno to find the reason.
}
                        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