This program:
#include <iostream>
#include <filesystem>
int main()
{
std::filesystem::path p1("c:\\");
std::filesystem::path p2("c:/");
if (p1.has_parent_path())
std::cout << "Parent path of " << p1 << " is " << p1.parent_path() << std::endl;
if (p2.has_parent_path())
std::cout << "Parent path of " << p2 << " is " << p2.parent_path() << std::endl;
}
Produces this output:
Parent path of "c:\\" is "c:\\"
Parent path of "c:/" is "c:/"
(EDIT: There was confusion about my use of forward slash so I updated this code to show the same thing happens regardless of which path separators you use on Windows)
This makes no sense to me. How can a directory be the parent of itself? What is the point of even having a "has_parent" function if it's never going to return false?
Most importantly: If I am writing code that recursively searches up a directory tree looking for a file, what is the best/most reliable way to detect that I've hit the root folder and should stop?
(I'm using Visual Studio 2019 in C++17 language mode, if that matters)
p.parentPath()
is the same asp
should work. Presumably,has_parent_path()
ofisolated_file.name
would returnfalse
. (Both ideas untested).