c++c++17std-filesystem

std::filesystem's parent_path() is wrong for file in current directory?


The traditional Unix shell utility, dirname, finds the name of the directory that contains the given file. This is useful if you want to find other sister files in the same directory. Here are a few examples:

$ dirname /some/dir/filename
/some/dir
$ dirname dirname/filename  
dirname
$ dirname filename
.

The new C++ std::filesystem's parent_path() gets this last one wrong (or so it appears):

#include <filesystem>
#include <iostream>
int main() {
    std::cout << "parent of filename: " <<
        std::filesystem::path("filename").parent_path() << '\n';
}

outputs:

parent of filename: ""

Returning an empty string instead of "." is not only different from the traditional dirname, it's also wrong when used in code which wants to tack on a "/..." on this parent to create the name of a sister files - this results in the wrong "/sister" instead of expected "./sister".

Is this a bug in std::filesystem, or deliberate behavior? Is the reason for this behavior documented somewhere?


Solution

  • I won't argue with you whether this is correct or not, but if you always use std::filesystem::operator/ instead of doing string manipulation, I don't see how you will run into the issue you mention in the question.

    In particular, std::filesystem::path("filename").parent_path()/std::filesystem::path("filename") gives you just "filename", not "/filename". I believe this is how the API is supposed to be used.