c++ - 编号的唯一文件

标签 c++ file

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

这是我想要做的,但是要使用目录(使用 <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/

    相关文章:

    c++ - c++读取文件省略换行符

    xml - 如何使用 XSLT 连接大量 XML 文件?

    c# - 使用校验和进行文件比较

    http - 如何以 "right"方式从 servlet 发送文件?

    c++ - 为什么switch不会在条件下执行

    c++ - 在 C 中更改指向数组的指针

    c++ - 使用assimp库时visual studio中未解析的外部符号

    c++ - OpenCV C++,定义背景模型

    c - 尝试声明字符串数组时出现 C 中的段错误。

    c - fscanf != eof Clang 编译器,异常行为