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?