Search code examples
c++qtboostfilepath

How to resolve a file path


I need to create a function that will remove anything such as '..' or '.' in a filepath. So if I did resolvePath("/root\\\\directory1/directory2\\\\\\\\..") it would return "root/directory1. I tried making a char* array of each part of the path but I couldn't get each segment of it.


Solution

  • The two really cross-platform alternatives are boost and Qt for this, so here goes it with both demonstrated:

    Boost solution: boost::filesystem::canonical

    path canonical(const path& p, const path& base = current_path());
    
    path canonical(const path& p, system::error_code& ec);
    
    path canonical(const path& p, const path& base, system::error_code& ec);
    

    Qt solution: QFileInfo

    QFileInfo fileInfo("/root\\\\directory1/directory2\\\\\\\\.."))
    
    qDebug() << fileInfo.canonicalFilePath();