我想创建唯一的文件,并在必要时在其名称后附加一个数字(类似于浏览器通常为下载文件命名的方式)。
这是我想要做的,但是要使用目录(使用 <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
}
如何处理文件?
一些精度:
mkstemp
-type函数,该函数需要在文件名先感谢您。
最佳答案
使用目录,您正在检查目录的创建是否可行。使用文件,您可以通过检查特定路径是否指向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/