¿Hay una manera más fácil de hacer estallar fuera de un directorio de sistema de archivos impulso :: :: camino?

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

  •  21-08-2019
  •  | 
  •  

Pregunta

Tengo una ruta relativa (por ejemplo, "foo / bar / baz / quux.xml") y quiero hacer estallar un directorio fuera de modo que voy a tener el subdirectorio + archivo (por ejemplo, "loquefuera / / quux.xml" ).

Puede hacer esto con iteradores de ruta, pero esperaba que hubiera algo que le faltaba a la documentación o algo más elegante. A continuación se muestra el código que he usado.

#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 salida es:

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

Lo que esperaba era algo como:

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

Si nos fijamos en algunos href="http://codepad.org/2h0V1HE0" rel="nofollow en codepad.org , me han tratado branch_path (retornos "foo / bar / baz ") y RELATIVE_PATH (retornos "foo / bar / baz / quux.xml").

¿Fue útil?

Solución

Aquí hay algo que un compañero de trabajo descubrió simplemente usando string::find con boost::filesystem::slash. Me gusta este que no requiere iterar por todo el recorrido hasta romperlo, sino también utilizando la definición independiente del sistema operativo de la trayectoria del carácter de separación camino. Gracias 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));
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top