我有一个相对路径(例如“foo/bar/baz/quux.xml”),并且我想弹出一个目录,以便我将拥有子目录+文件(例如“bar/baz/quux.xml”) )。
您可以使用路径迭代器来完成此操作,但我希望文档中缺少一些东西或更优雅的东西。下面是我使用的代码。
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem/exception.hpp>
#include <boost/assign.hpp>
boost::filesystem::path pop_directory(const boost::filesystem::path& path)
{
list<string> parts;
copy(path.begin(), path.end(), back_inserter(parts));
if (parts.size() < 2)
{
return path;
}
else
{
boost::filesystem::path pathSub;
for (list<string>::iterator it = ++parts.begin(); it != parts.end(); ++it)
{
pathSub /= *it;
}
return pathSub;
}
}
int main(int argc, char* argv)
{
list<string> test = boost::assign::list_of("foo/bar/baz/quux.xml")
("quux.xml")("foo/bar.xml")("./foo/bar.xml");
for (list<string>::iterator i = test.begin(); i != test.end(); ++i)
{
boost::filesystem::path p(*i);
cout << "Input: " << p.native_file_string() << endl;
boost::filesystem::path p2(pop_directory(p));
cout << "Subdir Path: " << p2.native_file_string() << endl;
}
}
输出为:
Input: foo/bar/baz/quux.xml
Subdir Path: bar/baz/quux.xml
Input: quux.xml
Subdir Path: quux.xml
Input: foo/bar.xml
Subdir Path: bar.xml
Input: ./foo/bar.xml
Subdir Path: foo/bar.xml
我所希望的是这样的:
boost::filesystem::path p1(someString);
boost::filesystem::path p2(p2.pop());
如果你看一些test code on codepad.org ,我尝试过branch_path(返回“foo/bar/baz”)和relative_path(返回“foo/bar/baz/quux.xml”)。
最佳答案
这是一位同事通过使用 string::find
和 boost::filesystem::slash
得出的结论。我喜欢这一点,因为它不需要迭代整个路径来分解它,而且还使用路径的独立于操作系统的路径分隔字符定义。谢谢博德根!
boost::filesystem::path pop_front_directory(const boost::filesystem::path& path)
{
string::size_type pos = path.string().find(boost::filesystem::slash<boost::filesystem::path>::value);
if (pos == string::npos)
{
return path;
}
else
{
return boost::filesystem::path(path.string().substr(pos+1));
}
}
关于c++ - 有没有更简单的方法从 boost::filesystem::path 弹出目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1070333/