c++std-filesystem

How to get the last directory in a std::filesystem::path?


I have a path to a directory and I want to get the name of that directory, using C++'s std::filesystem. For example, if the path was:

std::filesystem::path fake_path("C:\\fake\\path\\to\\my_directory\\");

I would want to get "my_directory".

I've seen this answer and initially assumed that what worked in boost::filesystem wasn't working in std::filesystem, though that may not be correct. Either way, I don't believe this is a duplicate because that one is specifically asking about boost::filesystem and a path that ends in a file.

I can think of several other solutions, like getting fake_path.end() - 2 or getting the string and splitting on the separator, but none of them are quite as simple as fake_path.filename() would've been.

Is there a clean way of getting the last part of a directory's path, roughly equivalent to calling .filename() on a file's path?


Solution

  • You could obtain it using:

    fake_path.parent_path().filename()