How does boost::filesystem::unique_path() resolve the need in mkstemp analogue in C++?

倖福魔咒の 提交于 2021-01-28 05:42:13

问题


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

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

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.

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


回答1:


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

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:

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.

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

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.



来源:https://stackoverflow.com/questions/43946120/how-does-boostfilesystemunique-path-resolve-the-need-in-mkstemp-analogue-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!