我boost::filesystem::path手头有一点,我想在它上面添加一个字符串(或路径).
boost::filesystem::path p("c:\\dir");
p.append(".foo"); // should result in p pointing to c:\dir.foo
Run Code Online (Sandbox Code Playgroud)
唯一的过载boost::filesystem::path有append需要打两次InputIterator秒.
到目前为止,我的解决方案是执行以下操作:
boost::filesystem::path p2(std::string(p.string()).append(".foo"));
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
hka*_*ser 61
如果它只是你想要改变的文件扩展名,那么你可能最好写一下:
p.replace_extension(".foo");
Run Code Online (Sandbox Code Playgroud)
对于大多数其他文件路径操作,您可以使用运算符/=并/允许连接名称的各个部分.例如
boost::filesystem::path p("c:\\dir");
p /= "subdir";
Run Code Online (Sandbox Code Playgroud)
会参考c:\dir\subdir.
小智 31
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
int main() {
boost::filesystem::path p (__FILE__);
std::string new_filename = p.leaf() + ".foo";
p.remove_leaf() /= new_filename;
std::cout << p << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
测试1.37,但leaf和remove_leaf也记录在1.35中.你需要先测试p的最后一个组件是否是文件名,如果不是的话.
使用Filesytem库的第3版(Boost 1.55.0),它就像它一样简单
boost::filesystem::path p("one_path");
p += "_and_another_one";
Run Code Online (Sandbox Code Playgroud)
导致p = "one_path_and_another_one".
您可以自己定义+运算符,以便添加两个boost::filesystem::path变量。
inline boost::filesystem::path operator+(boost::filesystem::path left, boost::filesystem::path right){return boost::filesystem::path(left)+=right;}
Run Code Online (Sandbox Code Playgroud)
然后你甚至可以添加一个std::string变量(隐式转换)。这类似于operator/from的定义
包含/boost/文件系统/path.hpp:
inline path operator/(const path& lhs, const path& rhs) { return path(lhs) /= rhs; }
Run Code Online (Sandbox Code Playgroud)
这是一个工作示例:
主要.cpp:
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
inline path operator+(path left, path right){return path(left)+=right;}
int main() {
path p1 = "/base/path";
path p2 = "/add/this";
std::string extension=".ext";
std::cout << p1+p2+extension << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译为
g++ main.cpp -lboost_system -lboost_filesystem
Run Code Online (Sandbox Code Playgroud)
产生输出:
$ ./a.out
"/base/path/add/this.ext"
Run Code Online (Sandbox Code Playgroud)