在linux上创建等效的CreateFile CREATE_NEW
CreateFile CREATE_NEW equivalent on linux
我写了一个方法,试图创建一个文件。然而,我设置了标志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_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.
}
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完全一样。
它将创建一个新的文件,你正在寻找。
相关文章:
- Using C++ CryptAPI:CNG Create CSR
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- createFile() 和 DeviceIoControl() 等效于 Unix/Linux 中的卷设备
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- QThread::create 似乎没有将参数传递给函数
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- QThread::create running on UI Thread
- 空指针(为缺少的输出数组调用的 create() 在 create,文件 /home/m/OpenCV/modules/
- 使用宏替换工厂模式样式 API 中的"create()"函数
- 错误:'create'不是 'cv::Tracker' 的成员
- Gtk::Main 和 Gtk::Application::create 有什么区别?
- CreateFile 在尝试打开目录进行读取时始终返回错误 5(访问被拒绝)
- 如果它被定义为 C++ 类中的成员函数,我得到了"non-standard syntax; use '&' to create a pointer to member"
- libgit2:git_clone() 失败并出现"failed to create ssl object"错误
- CreateProcess vs. CreateFile EXE
- 使用c_str时"Use & to create a pointer to a member"
- OGRE-找不到请求的发射极类型.在promentystemmanager中:: _ create -emitter
- Visual Studio 2015:获取"non standard syntax, use '&' to create a pointer to member"错误
- 用CreateFile打开显示时,正确的路径是什么?
- 为什么我无法使用CreateFile Win32 API打开文件RW,但可以使用STD ::删除将其删除