Question

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.

Was it helpful?

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();

OTHER TIPS

It looks from the example path you gave that you're on a Unix-like system. You can use realpath() to canonicalize your path then. This exists on Linux, BSD and Mac OS at least.

http://man7.org/linux/man-pages/man3/realpath.3.html

A working solution is now available from the standard libary (C++17):

#include <iostream>
#include <filesystem>
int main()
{
    // resolves based on current dir
    std::filesystem::path mypath = std::filesystem::canonical("../dir/file.ext");
    std::cout << mypath.generic_string(); // root/parent_dir/dir/file.ext
    return 0;
}

Documentation:

https://en.cppreference.com/w/cpp/filesystem/canonical

https://en.cppreference.com/w/cpp/header/filesystem

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top