【问题标题】:What is the right way to add secondary extension to boost::filesystem::path?将辅助扩展添加到 boost::filesystem::path 的正确方法是什么?
【发布时间】:2016-11-07 12:32:38
【问题描述】:

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

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

预期行为:

  • append_extension("foo.txt", ".log") -> "foo.txt.log"
  • append_extension("foo.txt", "log") -> "foo.txt.log"
  • append_extension("foo", "log") -> "foo.log"

是否可以实现append_extension 不使用点字符进行字符串操作?

【问题讨论】:

  • 如果您发布“示例代码”,最好让它在语法上正确。
  • replace_extension 有帮助吗?
  • replace_extension 不保留第一个扩展名。在“ext”参数中没有点的情况下,运算符 += 工作不正确。

标签: c++ boost boost-filesystem


【解决方案1】:

怎么样

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;
}

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

没有。扩展不是一件事,它们只是约定。次要扩展甚至都不是约定俗成的,所以你只能靠自己。

演示

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"

【讨论】:

  • 您的答案看起来不错,但它为第一个样本返回了意外的结果(两个连续的点)。请注意,对于 path::replace_extension 方法,可以像使用点一样指定扩展名,也可以不使用。
  • 你说的很对。当然,您可以检测到尾随点并禁止多余的点。更新答案
  • 我几乎准备好接受了,但请您解释一下,path.string&lt;std::string&gt;() 的原因是什么?为什么不path::string()
  • 还有一条评论:在您的实现中,path 参数可能被声明为 const 引用。
  • 是的。我曾经玩弄过一个就地更新它的变体(使用boost::property_tree::string_path&lt;std::string&gt;),但我决定反对它
猜你喜欢
  • 2011-01-24
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 1970-01-01
  • 2016-06-02
  • 2020-08-18
  • 1970-01-01
相关资源
最近更新 更多