在Linux上CreateFile CREATE_NEW等价物

我写了一个方法,试图创build一个文件。 不过,我将CREATE_NEW标志设置为只能在不存在时创build。 它看起来像这样:

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)); } 

这工作,因为它应该。 现在我想把它移植到linux上,当然CreateFile函数只能用于windows。 所以我正在寻找相当于这个东西,但在Linux上。 我已经看了open(),但我似乎找不到像CREATE_NEW一样的标志。 有谁知道这个解决scheme?

看看open() 页 , O_CREATO_EXCL的组合就是你正在寻找的东西。

例:

 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. } 
 fd = open("path/to/file", O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC); O_CREAT: Creates file if it does not exist. If the file exists, this flag has no effect. O_EXCL: If O_CREAT and O_EXCL are set, open() will fail if the file exists. O_RDWR: Open for reading and writing. 

另外,creat()等于open(),标志等于O_CREAT | O_WRONLY | O_TRUNC。

检查这个: http : //linux.die.net/man/2/open

这是正确和可行的答案:

 #include <fcntl2.h> // open #include <unistd.h> // pwrite //O_CREAT: Creates file if it does not exist.If the file exists, this flag has no effect. //O_EXCL : If O_CREAT and O_EXCL are set, open() will fail if the file exists. //O_RDWR : Open for reading and writing. int file = open("myfile.txt", O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC); if (file >= 0) { // File successfully created. ssize_t rc = pwrite(file, "your data", sizeof("myfile.txt"), 0); } else { // Error occurred. Examine errno to find the reason. } 

我发布了这个代码给另一个人,在一个评论里面,因为他的问题是关闭的…但是这个代码在Ubuntu上被我测试,它的工作方式与CreateFileA和WriteFile完全一样。

它会创建一个新的文件,你正在寻找。