Boost :: FileSystem :: Path에서 디렉토리를 꺼내는 더 쉬운 방법이 있습니까?
-
21-08-2019 - |
문제
상대 경로 (예 : "foo/bar/baz/quux.xml")가 있고 서브 디렉토리 + 파일 (예 : "bar/baz/quux.xml")을 갖도록 디렉토리를 꺼내고 싶습니다.
Path Iterators 로이 작업을 수행 할 수 있지만 문서에서 빠진 것이 있거나 더 우아한 것이 있기를 바랍니다. 아래는 내가 사용한 코드입니다.
#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 (returns "foo/bar/baz") 및 regal_path (returns "foo/bar/baz/quux.xml")를 시도했습니다.
해결책
다음은 동료가 string::find
~와 함께 boost::filesystem::slash
. 나는 전체 경로를 반복 할 필요가 없으며 경로 분리 문자에 대한 경로의 OS 독립적 정의를 사용하는 것이 좋습니다. 감사합니다 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));
}
}
제휴하지 않습니다 StackOverflow