32 auto path = std::filesystem::path(name);
33 auto parent_path = path.parent_path();
34 std::string stem = path.stem();
35 std::string extension = path.extension();
38 auto get_alternate_file_stem = [](std::string& file_stem,
39 const std::size_t n) {
40 const std::string delim{
"_"};
44 std::size_t pos{file_stem.rfind(delim)};
45 if (pos == std::string::npos || (pos + 1 == file_stem.size())) {
46 throw std::runtime_error(
"Malformed file name");
51 file_stem.replace(pos, file_stem.size() - pos, std::to_string(n));
56 return file_stem + delim + std::to_string(n);
59 std::size_t n_trials{2u};
60 while (std::filesystem::exists(path)) {
61 stem = get_alternate_file_stem(stem, n_trials);
62 path = parent_path / std::filesystem::path{stem + extension};
66 if (n_trials >= 10000u) {
67 throw std::runtime_error(
"Too many versions of file exist: " + stem +
72 path = parent_path / std::filesystem::path{stem + extension};
80 auto path = std::filesystem::path(outdir);
82 if (!path.empty() && !std::filesystem::exists(path)) {
83 if (std::error_code err; !std::filesystem::create_directories(path, err)) {
84 throw std::runtime_error(err.message());
std::string alt_file_name(const std::string &name)
Find an unused numbered alternative to an existing file name.
Definition create_path.hpp:31
auto create_path(const std::string &outdir)
Check if a given file path exists and generate it if not.
Definition create_path.hpp:79