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?
Christian Aichinger :
Take a look at the open() manpage, the combination of O_CREAT and O_EXCL is what you are looking for.\n\nExample:\n\nmode_t perms = S_IRWXU; // Pick appropriate permissions for the new file.\nint fd = open(\"file\", O_CREAT|O_EXCL, perms);\nif (fd >= 0) {\n // File successfully created.\n} else {\n // Error occurred. Examine errno to find the reason.\n}\n",
2014-04-15T13:20:14
Liviu Gheorghisan :
fd = open(\"path/to/file\", O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC);\n\nO_CREAT: Creates file if it does not exist. If the file exists, this flag has no effect.\nO_EXCL: If O_CREAT and O_EXCL are set, open() will fail if the file exists.\nO_RDWR: Open for reading and writing.\n\n\nAlso, creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC.\n\nCheck this: http://linux.die.net/man/2/open",
2014-04-15T13:29:45