gpt4 book ai didi

c++ - 编号的唯一文件

转载 作者:行者123 更新时间:2023-12-02 10:33:04 27 4
gpt4 key购买 nike

我想创建唯一的文件,并在必要时在其名称后附加一个数字(类似于浏览器通常为下载文件命名的方式)。

这是我想要做的,但是要使用目录(使用 <filesystem> 库):

#include <filesystem>
namespace fs = std::filesystem;

template <typename... Args> std::string concatenate(Args&&... args) {
std::ostringstream sstr;
(sstr << ... << std::forward<Args>(args));
return sstr.str();
}

fs::path unique_dir(const fs::path &base, unsigned max_tries) {
if(fs::create_directories(base))
return base;

for(unsigned i = 1; i < max_tries; ++i) {
fs::path p = base;
p += concatenate('_', i);

if(fs::create_directory(p))
return p;
}

throw std::runtime_error("unique_dir: gave up");
}

int main() {
unique_dir("my_dir", 3); // creates my_dir
unique_dir("my_dir", 3); // creates my_dir_1
unique_dir("my_dir", 3); // creates my_dir_2
unique_dir("my_dir", 3); // throws
}

如何处理文件?

一些精度:
  • 不需要是高性能的(这是代码的非常冷的部分)
  • 只要可以在Linux,Windows和Mac上使用变体,就可以使用非跨平台的
  • 我不想使用 mkstemp -type函数,该函数需要在文件名
  • 中放置非用户友好的id

    先感谢您。

    最佳答案

    使用目录,您正在检查目录的创建是否可行。使用文件,您可以通过检查特定路径是否指向existing文件来实现此效果,如果没有,则创建该文件:

    fs::path unique_file(const fs::path &base, unsigned max_tries) {
    if(!fs::exists(base)) {
    std::ofstream ofs(base);
    return base;
    }

    for(unsigned i = 1; i < max_tries; ++i) {
    fs::path p = base;
    p += concat() << '_' << i;

    if(!fs::exists(p)) {
    std::ofstream ofs(p);
    return p;
    }
    }

    throw std::runtime_error("unique_file: gave up");
    }

    关于c++ - 编号的唯一文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61546653/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com