我写了一个尝试创建文件的方法。但是我设置了标志 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()
manpage ,O_CREAT
和 O_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.
}
关于c++ - Linux 上的 CreateFile CREATE_NEW 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23084914/