0

When setting a path by passing just a file name to mean, the path is current_path() + filename, it seems std::filesystem::path recognizes a parent path only when explicitly given as relative path. Its easier to explain with code - the following code with give the below output:

#include <iostream>
#include <filesystem>
using namespace std;

int main()
{
    std::filesystem::path firstPath{"myFile1.txt"};
    std::cout<<"absolute first path:"<<absolute(firstPath).lexically_normal()<<std::endl;
    if(firstPath.has_parent_path()) {
        std::cout<<"parent of "<<firstPath<<" is "<<firstPath.parent_path()<<std::endl;
    }
    else {
        std::cout<<firstPath<<" has no parent"<<std::endl;
    }
    
    
    std::filesystem::path secondPath{"./myFile2.txt"};
    std::cout<<"absolute second path:"<<absolute(secondPath).lexically_normal()<<std::endl;
    if(secondPath.has_parent_path()) {
        std::cout<<"parent of "<<secondPath<<" is "<<secondPath.parent_path()<<std::endl;
    }
    else {
        std::cout<<secondPath<<" has not parent"<<std::endl;
    }
    
    firstPath = absolute(firstPath).string();
    
    if(firstPath.has_parent_path()) {
        std::cout<<"after self string assignment, parent of "<<firstPath<<" is "<<firstPath.parent_path()<<std::endl;
    }
    else {
        std::cout<<firstPath<<"after self string assignment, first path still has not parent"<<std::endl;
    }
    
    
    return 0;
}

The output is:

 absolute first path:"/home/myFile1.txt"
"myFile1.txt" has not parent
absolute second path:"/home/myFile2.txt"
parent of "./myFile2.txt" is "."
after self string assignment, parent of "/home/myFile1.txt" is "/home"

so while it seems in both cases the absolute path is constructed as expected, depending if the given path was with "./" or without it, the has_parent() and the parent_path() return the parent path or not. In addition, note that the second path parent is "." and not /home even-though the absolute path is correct.

If setting just "myFile1.txt" would also not yield a correct absolute path I would have had no issues with the behavior but since the absolute path is correct in both cases but the relative path not - and - in addition, setting the path from its own absolute string (the one that did not see a parent) makes the parent_path() see the parent path, I wonder if this is intended behavior or a bug?

Do any of you know?

Many thanks!

dkish
  • 319
  • 3
  • 13
  • It's by design. Member functions of `path` only care about how the path is spelled, while non-member functions in `std::filesystem` (such as `absolute`) actually communicate with the OS to see what the path *means*. – cpplearner Sep 15 '22 at 16:07
  • Ok, thanks! but it still does not explain why no parent_path() is seen... or does it and I don't see how? – dkish Sep 15 '22 at 16:12

0 Answers0