2

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.

László Papp
  • 51,870
  • 39
  • 111
  • 135
user3103398
  • 143
  • 9
  • 1
    any reason not to use boost::filesystem? – odedsh Apr 20 '14 at 13:40
  • What do you mean? I am using it for an emulator and one of the functions is this. – user3103398 Apr 20 '14 at 13:41
  • You really need to post what you've tried so far and be more specific about where you got stuck. – M.M Apr 20 '14 at 13:41
  • 1
    Take a look at http://stackoverflow.com/questions/1746136/how-do-i-normalize-a-pathname-using-boostfilesystem and read documentation about "canonical" function in boost::filesystem – odedsh Apr 20 '14 at 13:42

3 Answers3

4

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();
László Papp
  • 51,870
  • 39
  • 111
  • 135
2

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

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

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