向 boost::filesystem::path 添加二级扩展的正确方法是什么?

What is the right way to add secondary extension to boost::filesystem::path?

我想为路径添加额外的扩展名:

namespace fs = boost::filesystem;
fs::path append_extension(const fs::path& path, const fs::path& ext);

预期行为:

是否可以在不使用点字符进行字符串操作的情况下实现 append_extension

怎么样

namespace fs = boost::filesystem;
fs::path append_extension(const fs::path& path, const fs::path& ext) {
    auto sz_ext = ext.c_str();
    if ('.' == *sz_ext) ++sz_ext;
    return path.string<std::string>() + "." + sz_ext;
}

Is it possible to implement append_extension without string manipulations with dot character?

没有。扩展不是一回事,它们只是约定。二次扩展甚至都不是惯例,所以你要靠自己了。

演示

Live On Coliru

#include <boost/filesystem.hpp>
#include <boost/property_tree/string_path.hpp>

namespace fs = boost::filesystem;
fs::path append_extension(const fs::path& path, const fs::path& ext) {
    auto sz_ext = ext.c_str();
    if ('.' == *sz_ext) ++sz_ext;
    return path.string<std::string>() + "." + sz_ext;
}
#include <iostream>

int main() {
    std::cout << append_extension("foo.txt", ".log") << "\n"; // -> "foo.txt.log"
    std::cout << append_extension("foo.txt", "log") << "\n"; // -> "foo.txt.log"
    std::cout << append_extension("foo", "log") << "\n"; // -> "foo.log"
}

版画

"foo.txt.log"
"foo.txt.log"
"foo.log"