相対パス(例: "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());
codepad.orgのテストコードを見ると、branch_path(「foo / bar / baz」を返す)とrelative_path(「foo / bar / baz / quux.xml」を返す)を試しました。