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 ofO_CREAT
andO_EXCL
is what you are looking for.Example:
This is the correct and working answer:
I posted this code for another person, inside a comment because his question is closed... but this code is tested by me on Ubuntu and it's working exactly as CreateFileA and WriteFile.
It will create a new file as you are seeking.
Also, creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC.
Check this: http://linux.die.net/man/2/open