Подтвердить что ты не робот

Получить относительный путь от двух абсолютных путей

У меня есть два абсолютных пути файловой системы (A и B), и я хочу создать третий путь к файловой системе, который представляет "Относительный от B".

Случай использования:

  • Медиаплеер, управляющий списком воспроизведения.
  • Пользователь добавляет файл в список воспроизведения.
  • Новый путь к файлу добавлен в список воспроизведения относительно пути к списку воспроизведения.
  • В будущем весь музыкальный каталог (включая плейлист) переместился в другое место.
  • Все пути все еще действительны, поскольку они относятся к списку воспроизведения.

boost::filesystem похоже, имеет complete, чтобы разрешить relative ~ relative => absolute, но ничего не делать в обратном порядке (absolute ~ absolute => relative).

Я хочу сделать это с помощью путей Boost.

4b9b3361

Ответ 1

Начиная с версии 1.60.0, boost.filesystem поддерживает это. Вы ищете path lexically_relative(const path& p) const функции-члену path lexically_relative(const path& p) const.

Оригинал, до 1.60.0 ответ ниже.


Boost не поддерживает это; это открытая проблема - # 1976 (обратная функция для завершения), которая, тем не менее, кажется, не получает большой тяги.

Вот смутно наивный обходной путь, который, кажется, делает свое дело (не уверен, можно ли его улучшить):

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
#include <stdexcept>

/**
 * https://svn.boost.org/trac/boost/ticket/1976#comment:2
 * 
 * "The idea: uncomplete(/foo/new, /foo/bar) => ../new
 *  The use case for this is any time you get a full path (from an open dialog, perhaps)
 *  and want to store a relative path so that the group of files can be moved to a different
 *  directory without breaking the paths. An IDE would be a simple example, so that the
 *  project file could be safely checked out of subversion."
 * 
 * ALGORITHM:
 *  iterate path and base
 * compare all elements so far of path and base
 * whilst they are the same, no write to output
 * when they change, or one runs out:
 *   write to output, ../ times the number of remaining elements in base
 *   write to output, the remaining elements in path
 */
boost::filesystem::path
naive_uncomplete(boost::filesystem::path const p, boost::filesystem::path const base) {

    using boost::filesystem::path;
    using boost::filesystem::dot;
    using boost::filesystem::slash;

    if (p == base)
        return "./";
        /*!! this breaks stuff if path is a filename rather than a directory,
             which it most likely is... but then base shouldn't be a filename so... */

    boost::filesystem::path from_path, from_base, output;

    boost::filesystem::path::iterator path_it = p.begin(),    path_end = p.end();
    boost::filesystem::path::iterator base_it = base.begin(), base_end = base.end();

    // check for emptiness
    if ((path_it == path_end) || (base_it == base_end))
        throw std::runtime_error("path or base was empty; couldn't generate relative path");

#ifdef WIN32
    // drive letters are different; don't generate a relative path
    if (*path_it != *base_it)
        return p;

    // now advance past drive letters; relative paths should only go up
    // to the root of the drive and not past it
    ++path_it, ++base_it;
#endif

    // Cache system-dependent dot, double-dot and slash strings
    const std::string _dot  = std::string(1, dot<path>::value);
    const std::string _dots = std::string(2, dot<path>::value);
    const std::string _sep = std::string(1, slash<path>::value);

    // iterate over path and base
    while (true) {

        // compare all elements so far of path and base to find greatest common root;
        // when elements of path and base differ, or run out:
        if ((path_it == path_end) || (base_it == base_end) || (*path_it != *base_it)) {

            // write to output, ../ times the number of remaining elements in base;
            // this is how far we've had to come down the tree from base to get to the common root
            for (; base_it != base_end; ++base_it) {
                if (*base_it == _dot)
                    continue;
                else if (*base_it == _sep)
                    continue;

                output /= "../";
            }

            // write to output, the remaining elements in path;
            // this is the path relative from the common root
            boost::filesystem::path::iterator path_it_start = path_it;
            for (; path_it != path_end; ++path_it) {

                if (path_it != path_it_start)
                    output /= "/";

                if (*path_it == _dot)
                    continue;
                if (*path_it == _sep)
                    continue;

                output /= *path_it;
            }

            break;
        }

        // add directory level to both paths and continue iteration
        from_path /= path(*path_it);
        from_base /= path(*base_it);

        ++path_it, ++base_it;
    }

    return output;
}

Ответ 2

Я только что написал код, который может переводить абсолютный путь в относительный путь. Он работает во всех моих случаях использования, но я не могу гарантировать, что он безупречен.

Я сократил boost :: filesystem до 'fs' для удобства чтения. В определении функции вы можете использовать fs :: path :: current_path() в качестве значения по умолчанию для'lative_to '.

fs::path relativePath( const fs::path &path, const fs::path &relative_to )
{
    // create absolute paths
    fs::path p = fs::absolute(path);
    fs::path r = fs::absolute(relative_to);

    // if root paths are different, return absolute path
    if( p.root_path() != r.root_path() )
        return p;

    // initialize relative path
    fs::path result;

    // find out where the two paths diverge
    fs::path::const_iterator itr_path = p.begin();
    fs::path::const_iterator itr_relative_to = r.begin();
    while( itr_path != p.end() && itr_relative_to != r.end() && *itr_path == *itr_relative_to ) {
        ++itr_path;
        ++itr_relative_to;
    }

    // add "../" for each remaining token in relative_to
    if( itr_relative_to != r.end() ) {
        ++itr_relative_to;
        while( itr_relative_to != r.end() ) {
            result /= "..";
            ++itr_relative_to;
        }
    }

    // add remaining path
    while( itr_path != p.end() ) {
        result /= *itr_path;
        ++itr_path;
    }

    return result;
}

Ответ 3

Я просто думал об использовании boost::filesystem для той же задачи, но - поскольку мое приложение использует библиотеки Qt и Boost, я решил использовать Qt, которая выполняет эту задачу с одним простым методом QString QDir ::lativeFilePath (const QString & fileName ):

QDir dir("/home/bob");
QString s;

s = dir.relativeFilePath("images/file.jpg");     // s is "images/file.jpg"
s = dir.relativeFilePath("/home/mary/file.txt"); // s is "../mary/file.txt"

Это работает как очарование и спасло мне несколько часов моей жизни.

Ответ 4

С С++ 17 и его std::filesystem::relative, который развился от boost, это не составляет труда:

#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main()
{
    const fs::path base("/is/the/speed/of/light/absolute");
    const fs::path p("/is/the/speed/of/light/absolute/or/is/it/relative/to/the/observer");
    const fs::path p2("/little/light/races/in/orbit/of/a/rogue/planet");
    std::cout << "Base is base: " << fs::relative(p, base).generic_string() << '\n'
              << "Base is deeper: " << fs::relative(base, p).generic_string() << '\n'
              << "Base is orthogonal: " << fs::relative(p2, base).generic_string();
    // Omitting exception handling/error code usage for simplicity.
}

Выход (второй параметр является базовым)

Base is base: or/is/it/relative/to/the/observer
Base is deeper: ../../../../../../..
Base is orthogonal: ../../../../../../little/light/races/in/orbit/of/a/rogue/planet

Для сравнения он использует std::filesystem::path::lexically_relative. Отличие от чисто лексической функции заключается в том, что std::filesystem::relative разрешает символические ссылки и нормализует оба пути, используя std::filesystem::weakly_canonical (который был введен для relative) перед сравнением.

Ответ 5

Вот как я это делаю в библиотеке, которую я создаю поверх файловой системы boost:

Шаг 1: Определите "самый глубокий общий корень". В принципе, это как самый общий общий знаменатель для двух путей. Например, если у вас 2 пути: "C:\a\b\c\d" и "C:\a\b\c\l.txt", то общий корень, которым они делят, - "C:\a\Ь\с \".

Чтобы получить это, конвертируйте оба пути в каноническую форму абсолютного NOT (вы захотите сделать это для умозрительных путей и символических ссылок).

Шаг 2: Чтобы перейти от A к B, вы суффикс A с достаточным количеством копий "../", чтобы переместить дерево каталогов на общий корень, затем добавьте строку для B, чтобы спуститься по дереву к ней. В окнах вы можете иметь 2 пути без общего корня, поэтому переход от любого A к любому B не всегда возможен.

namespace fs = boost::filesystem;

bool GetCommonRoot(const fs::path& path1,
                       const fs::path& path2,
                       fs::path& routeFrom1To2,
                       std::vector<fs::path>& commonDirsInOrder)
{
   fs::path pathA( fs::absolute( path1));
   fs::path pathB( fs::absolute( path2));

   // Parse both paths into vectors of tokens. I call them "dir" because they'll
   // be the common directories unless both paths are the exact same file.
   // I also Remove the "." and ".." paths as part of the loops

   fs::path::iterator    iter;
   std::vector<fs::path> dirsA;
   std::vector<fs::path> dirsB;
   for(iter = pathA.begin(); iter != pathA.end(); ++iter) {
       std::string token = (*iter).string();
       if(token.compare("..") == 0) {      // Go up 1 level => Pop vector
          dirsA.pop_back();
       }
       else if(token.compare(".") != 0) {  // "." means "this dir" => ignore it
          dirsA.push_back( *iter);
       }
   }
   for(iter = pathB.begin(); iter != pathB.end(); ++iter) {
       std::string token = (*iter).string();
       if(token.compare("..") == 0) {      // Go up 1 level => Pop vector
          dirsB.pop_back();
       }
       else if(token.compare(".") != 0) {  // "." means "this dir" => ignore it
          dirsB.push_back( *iter);
       }
   }

   // Determine how far to check in each directory set
   size_t commonDepth = std::min<int>( dirsA.size(), dirsB.size());
   if(!commonDepth) {
       // They don't even share a common root- no way from A to B
       return false;
   }

   // Match entries in the 2 vectors until we see a divergence
   commonDirsInOrder.clear();
   for(size_t i=0; i<commonDepth; ++i) {
      if(dirsA[i].string().compare( dirsB[i].string()) != 0) {   // Diverged
         break;
      }
      commonDirsInOrder.push_back( dirsA[i]);  // I could use dirsB too.
   }

   // Now determine route: start with A
   routeFrom1To2.clear();
   for(size_t i=0; i<commonDepth; ++i) {
       routeFrom1To2 /= dirsA[i];
   }
   size_t backupSteps = dirsA.size() - commonDepth; // # of "up dir" moves we need
   for(size_t i=0; i<backupSteps; ++i) {
       routeFrom1To2 /= "../";
   }

   // Append B path to go down to it from the common root
   for(size_t i=commonDepth; i<dirsB.size(); ++i) {
       routeFrom1To2 /= dirsB[i];    // ensures absolutely correct subdirs
   }
   return true;

}

Это будет делать то, что вы хотите, - вы поднимаетесь с A до тех пор, пока не нажмете на общую папку, а B - оба потомка, а затем перейдите к B. Вам, вероятно, не нужен возврат "commonDirsInOrder", который у меня есть, но возврат "routeFrom1To2" - это тот, который вы запрашиваете.

Если вы планируете фактически изменить рабочий каталог на "B", вы можете напрямую использовать "routeFrom1To2". Имейте в виду, что эта функция создаст абсолютный путь, несмотря на все части "..", но это не должно быть проблемой.

Ответ 6

Я записал одно простое решение для этого трюка. Там нет использования на библиотеки повышения, только STL std::string, std::vector.

Платформа Win32 была протестирована.

Просто звоню:

strAlgExeFile = helper.GetRelativePath(PathA, PathB);

И это вернуло бы относительный путь от PathA к PathB.

Пример:

strAlgExeFile = helper.GetRelativePath((helper.GetCurrentDir()).c_str(), strAlgExeFile.c_str());

#ifdef _WIN32                                                                              
    #define STR_TOKEN "\\"                                                                 
    #define LAST_FOLDER "..\\"                                                             
    #define FOLDER_SEP "\\"                                                                
    #define LINE_BREAK "\r\n"                                                              
#else                                                                                      
    #define STR_TOKEN "/"                                                                  
    #define LAST_FOLDER "../"                                                              
    #define FOLDER_SEP "/"                                                                 
    #define LINE_BREAK "\n"                                                                
#endif // _WIN32                                                                           

void CHelper::SplitStr2Vec(const char* pszPath, vector<string>& vecString)                 
{                                                                                          
  char * pch;                                                                              

  pch = strtok (const_cast < char*> (pszPath), STR_TOKEN );                                
  while (pch != NULL)                                                                      
  {                                                                                        
    vecString.push_back( pch );                                                            
    pch = strtok (NULL, STR_TOKEN );                                                       
  }                                                                                        
}                                                                                          

string& CHelper::GetRelativePath(const char* pszPath1,const char* pszPath2)                
{                                                                                          
    vector<string> vecPath1, vecPath2;                                                     
    vecPath1.clear();                                                                      
    vecPath2.clear();                                                                      
    SplitStr2Vec(pszPath1, vecPath1);                                                      
    SplitStr2Vec(pszPath2, vecPath2);                                                      
    size_t iSize = ( vecPath1.size() < vecPath2.size() )? vecPath1.size(): vecPath2.size();
    unsigned int iSameSize(0);                                                             
    for (unsigned int i=0; i<iSize; ++i)                                                   
    {                                                                                      
        if ( vecPath1[i] != vecPath2[i])                                                   
        {                                                                                  
            iSameSize = i;                                                                 
            break;                                                                         
        }                                                                                  
    }                                                                                      

    m_strRelativePath = "";                                                                
    for (unsigned int i=0 ; i< (vecPath1.size()-iSameSize) ; ++i)                          
        m_strRelativePath += const_cast<char *> (LAST_FOLDER);                             

    for (unsigned int i=iSameSize ; i<vecPath2.size() ; ++i)                               
    {                                                                                      
        m_strRelativePath += vecPath2[i];                                                  
        if( i < (vecPath2.size()-1) )                                                      
            m_strRelativePath += const_cast<char *> (FOLDER_SEP);                          
    }                                                                                      

    return m_strRelativePath;                                                              
}

Ответ 7

Мне нужно было сделать это без Boost, а другое решение на базе std не делало этого для меня, поэтому я его повторно реализовал. Когда я работал над этим, я понял, что сделал это и раньше...

Во всяком случае, это не так полно, как некоторые из других, но может быть полезно людям. Это зависит от Windows; изменения, чтобы заставить POSIX включать разделитель каталогов и чувствительность к регистру в сравнении строк.

Вскоре после того, как я получил это и работал, мне пришлось перенести окружающие функции на Python, поэтому все это сводилось к os.path.relpath(to, from).

static inline bool StringsEqual_i(const std::string& lhs, const std::string& rhs)
{
    return _stricmp(lhs.c_str(), rhs.c_str()) == 0;
}

static void SplitPath(const std::string& in_path, std::vector<std::string>& split_path)
{
    size_t start = 0;
    size_t dirsep;
    do
    {
        dirsep = in_path.find_first_of("\\/", start);
        if (dirsep == std::string::npos)
            split_path.push_back(std::string(&in_path[start]));
        else
            split_path.push_back(std::string(&in_path[start], &in_path[dirsep]));
        start = dirsep + 1;
    } while (dirsep != std::string::npos);
}

/**
 * Get the relative path from a base location to a target location.
 *
 * \param to The target location.
 * \param from The base location. Must be a directory.
 * \returns The resulting relative path.
 */
static std::string GetRelativePath(const std::string& to, const std::string& from)
{
    std::vector<std::string> to_dirs;
    std::vector<std::string> from_dirs;

    SplitPath(to, to_dirs);
    SplitPath(from, from_dirs);

    std::string output;
    output.reserve(to.size());

    std::vector<std::string>::const_iterator to_it = to_dirs.begin(),
                                             to_end = to_dirs.end(),
                                             from_it = from_dirs.begin(),
                                             from_end = from_dirs.end();

    while ((to_it != to_end) && (from_it != from_end) && StringsEqual_i(*to_it, *from_it))
    {
         ++to_it;
         ++from_it;
    }

    while (from_it != from_end)
    {
        output += "..\\";
        ++from_it;
    }

    while (to_it != to_end)
    {
        output += *to_it;
        ++to_it;

        if (to_it != to_end)
            output += "\\";
    }

    return output;
}