在linux上创建等效的CreateFile CREATE_NEW

CreateFile CREATE_NEW equivalent on linux

本文关键字:CreateFile CREATE NEW linux 创建      更新时间:2023-10-16

我写了一个方法,试图创建一个文件。然而,我设置了标志CREATE_NEW,所以它只能在不存在时创建它。它看起来像这样:

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这样的标志。有人知道解决这个问题的办法吗?

查看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完全一样。

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