boost :: filesystem :: unique_path()如何解决C ++中mkstemp模拟的需求? [英] How does boost::filesystem::unique_path() resolve the need in mkstemp analogue in C++?

查看:123
本文介绍了boost :: filesystem :: unique_path()如何解决C ++中mkstemp模拟的需求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Boost的旧版功能请求正在请求与<可以在Boost.Filesystem中使用的href ="http://pubs.opengroup.org/onlinepubs/009695399/functions/mkstemp.html" rel ="nofollow noreferrer"> mkstemp POSIX函数.该问题已永久解决,并带有评论

An old feature request for Boost was requesting a feature similar to mkstemp POSIX function to be available in Boost.Filesystem. The issue is long closed as fixed, with the comment

第3版中的unique_path()函数解决了该问题.

The unique_path() function in Version 3 addresses the problem.

但是我看不到 unique_path 如何解决该问题.它与 tmpnam 基本相同:在生成名称并在创建实际文件之前,另一个程序可能已经创建了具有相同名称的文件.

But I fail to see how unique_path resolves the problem. It's basically the same as tmpnam: after the name has been generated and before actual file is created, another program may have created its file with the same name.

那么应该如何解决 mkstemp 中的需求?

So how is it supposed to address the need in mkstemp?

推荐答案

O_CREAT ,基本上说创建文件,如果它已经存在,则返回错误.

My guess is that the implementation (at least on *nix systems) could result in effectively calling open with O_EXCL | O_CREAT, which basically says "create the file, if it already exists, return an error.

因此,一个实现可能具有这样的算法:

So, an implementation could have an algorithm like this:

for(;;) {
    name = create_likley_unique_name();
    file = open(name, O_EXCL | O_CREAT, mode);
    if(valid(file)) {
        return file;
    }
}

这当然只是一种猜测,但我认为这是一个合理的假设.我不知道Windows或osx是否具有可比较的标志.

This is of course just a guess, but I think it is a reasonable one. I have no idea if windows or osx have a comparable flag.

我认为您链接的页面上解决方案"的关键部分是以下部分:

I think the key part of the "solution" on the page you linked is this part:

建议的解决方法是(1)重命名该函数,以及(2)提供一个如何通过fstream甚至C I/O安全使用该函数的示例.提议的措辞请见下文.

The suggested fix is to (1) rename the function and (2) provide an example of how to use the function safely with fstreams or even C I/O. See below for proposed wording.

一个合适的示例就像我刚写的一样,但是使用了等效的c ++ ish API.

Where a proper example would something like what I just wrote, but using an equivalent c++ish API.

请注意,在线程中,他们提供了将函数重命名为 generate_random_filename()的功能,由于该功能不可预测,因此更合适,但不能保证唯一.但也建议使用 create_unique_file(),它可能会实现类似于我的示例的算法.

Note that in the thread they offer renaming the function to generate_random_filename(), which is more appropriate given that it is unpredictable, but not guaranteed to be unique. But also suggest a create_unique_file(), which would likely implement an algorithm similar to my example.

这篇关于boost :: filesystem :: unique_path()如何解决C ++中mkstemp模拟的需求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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