2

I have a file in my home directory:

~/abc.csv

I want to get the complete absolute path which would be:

/home/nishant/abs.csv

How do I get it?

I thought canonical would help, but for canonical to work, the file should exists, and the exists function on ~/abc.csv returns false.

Wtower
  • 18,848
  • 11
  • 103
  • 80
Nishant Sharma
  • 341
  • 2
  • 5
  • 17

1 Answers1

2

This is not making the path absolute, nor making it canonical.

It's shell expansion of the ~ character. And it's not a feature in Boost Filesystem, as such.

You can code it yourself:

Live On Coliru

#include <boost/filesystem.hpp>
#include <iostream>

using boost::filesystem::path;

path expand(path p) {
    char const* const home = getenv("HOME");
    if (home == nullptr)
        return p; // TODO handle as error?

    auto s = p.generic_string<std::string>();
    if (!s.empty() && s.find("~/") == 0u) {
        return home + s.substr(1);
    }
    return p;
}


int main() {
    path sample = "~/test.cpp";
    std::cout << expand(sample) << "\n";
}

Which, on my system prints "/home/sehe/test.cpp"

sehe
  • 374,641
  • 47
  • 450
  • 633