std::fstream / std::filesystem 创建具有重复编号的文件
std::fstream / std::filesystem create file with duplicate number
我想创建一个文件末尾有一个数字的文件:
filename ( number goes here ).txt
。该数字将告诉我文件创建目录中是否存在重复文件:filename.txt
.
示例:helloworld (1).txt
Windows 在尝试创建文件副本时也具有此功能。我可以在 C++ 17 中做到这一点吗?
由于没有人给我任何答案,我决定花一些时间在这个函数上做我想做的事,并回答我自己的问题,它在 C++ 17 中适用于任何认为这有用的人:
#include <filesystem>
#include <regex>
#include <fstream>
#include <string>
namespace fs = std::filesystem;
// Just file "std::ostream::open()" except it handles duplicates too
void create_file_dup(std::string path)
{
// Check if file doesnt have duplicates
if (!fs::exists(path)) {
std::ofstream(path);
return;
}
// Get filename without path
std::string filename = (fs::path(path).filename()).string();
// Since its already a duplicate add "(1)" inbetween the basename and extension
filename = (fs::path(filename).stem()).string() + " (1)" + (fs::path(filename).extension()).string();
// Get file's parent directory
std::string parent = (fs::path(path).parent_path()).string();
// Loops to check for more duplicates
for (int dup_count = 2;!fs::exists(parent + filename);dup_count++) {
std::string dup_c = "(" + std::to_string(dup_count); // old number
dup_c + ")";
std::string dup_cn = "(" + std::to_string(dup_count + 1); // new number
dup_cn + ")";
filename = std::regex_replace(filename, std::regex(dup_c), dup_cn); // increments : '(1)' -> '(2)'
}
// We have found the how many duplicates there are , so create the file with the duplicate number
std::ofstream(parent + filename);
return;
}
我想创建一个文件末尾有一个数字的文件:
filename ( number goes here ).txt
。该数字将告诉我文件创建目录中是否存在重复文件:filename.txt
.
示例:helloworld (1).txt
Windows 在尝试创建文件副本时也具有此功能。我可以在 C++ 17 中做到这一点吗?
由于没有人给我任何答案,我决定花一些时间在这个函数上做我想做的事,并回答我自己的问题,它在 C++ 17 中适用于任何认为这有用的人:
#include <filesystem>
#include <regex>
#include <fstream>
#include <string>
namespace fs = std::filesystem;
// Just file "std::ostream::open()" except it handles duplicates too
void create_file_dup(std::string path)
{
// Check if file doesnt have duplicates
if (!fs::exists(path)) {
std::ofstream(path);
return;
}
// Get filename without path
std::string filename = (fs::path(path).filename()).string();
// Since its already a duplicate add "(1)" inbetween the basename and extension
filename = (fs::path(filename).stem()).string() + " (1)" + (fs::path(filename).extension()).string();
// Get file's parent directory
std::string parent = (fs::path(path).parent_path()).string();
// Loops to check for more duplicates
for (int dup_count = 2;!fs::exists(parent + filename);dup_count++) {
std::string dup_c = "(" + std::to_string(dup_count); // old number
dup_c + ")";
std::string dup_cn = "(" + std::to_string(dup_count + 1); // new number
dup_cn + ")";
filename = std::regex_replace(filename, std::regex(dup_c), dup_cn); // increments : '(1)' -> '(2)'
}
// We have found the how many duplicates there are , so create the file with the duplicate number
std::ofstream(parent + filename);
return;
}