在Linux上等效的CreateFile CREATE_NEW [英] CreateFile CREATE_NEW equivalent on linux

查看:919
本文介绍了在Linux上等效的CreateFile CREATE_NEW的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个尝试创建文件的方法.但是我设置了标志CREATE_NEW,因此它只能在不存在时创建.看起来像这样:

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

这可以正常工作.现在我想将其移植到linux,当然CreateFile函数仅适用于Windows.因此,我正在Linux上寻找与之等效的东西.我已经看过open()了,但是似乎找不到像CREATE_NEW一样的标志.有人知道解决方案吗?

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?

推荐答案

看看open()

Take a look at the open() manpage, the combination of O_CREAT and O_EXCL is what you are looking for.

示例:

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.
}

这篇关于在Linux上等效的CreateFile CREATE_NEW的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆