Y at-il un moyen plus facile pour faire sauter un répertoire de boost :: système de fichiers :: chemin?

StackOverflow https://stackoverflow.com/questions/1070333

  •  21-08-2019
  •  | 
  •  

Question

J'ai un chemin relatif (par exemple « foo / bar / baz / quux.xml ») et je veux pop un répertoire de sorte que je vais avoir le sous-répertoire + fichier (par exemple, « bar / baz / quux.xml » ).

Vous pouvez le faire avec chemin itérateurs, mais j'espérais qu'il y avait quelque chose que je manque de la documentation ou quelque chose de plus élégant. Voici le code que je.

#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;
  }
}

La sortie est la suivante:

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

Ce que j'espérais était quelque chose comme:

boost::filesystem::path p1(someString);
boost::filesystem::path p2(p2.pop());

Si vous regardez certains de href="http://codepad.org/2h0V1HE0" sur codepad.org , j'ai essayé branch_path (retours « foo / bar / baz ") et RELATIVE_PATH (rendements "foo / bar / baz / quux.xml").

Était-ce utile?

La solution

Voici quelque chose qu'un collègue a compris que l'utilisation avec string::find boost::filesystem::slash. J'aime ce qu'il ne nécessite pas itérateur sur le chemin complet casser, mais aussi en utilisant la définition du système d'exploitation indépendant du chemin du caractère de séparation de chemin. Merci 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));
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top