Gibt es einen einfacheren Weg, um ein Verzeichnis von boost :: filesystem :: Weg zur Pop-off?
-
21-08-2019 - |
Frage
Ich habe einen relativen Pfad (zB „foo / bar / baz / quux.xml“) und ich möchte aus einem Verzeichnis Pop, so dass ich das Unterverzeichnis haben + Datei (zB „bar / baz / quux.xml“ ).
Sie können dies tun, mit Pfad Iteratoren, aber ich hatte gehofft, es war etwas, was ich aus der Dokumentation oder etwas elegantere fehlt. Unten ist der Code, die ich verwendet.
#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;
}
}
Die Ausgabe lautet:
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
Was ich hatte gehofft, für etwas wie:
boost::filesystem::path p1(someString);
boost::filesystem::path p2(p2.pop());
Wenn Sie irgend Testcode auf codepad.org , habe ich versucht, branch_path (returns „foo / bar / baz ") und relativer_Pfad (returns "foo / bar / baz / quux.xml").
Lösung
Hier ist etwas, das ein Mitarbeiter nur string::find
mit boost::filesystem::slash
mit herausgefunden. Ich mag das, dass es nicht Iterierte über den gesamten Weg erforderlich macht es zu brechen, sondern auch den Weg des OS-unabhängige Definition der Pfadtrennzeichen verwenden. Dank Bodgan!
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));
}
}