13

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?

Withad
  • 503
  • 1
  • 6
  • 12
  • Does this answer your question? [how to use C++ to get the folder/directory name, but not the path of one file? Especially boost::filesystem;](https://stackoverflow.com/questions/39275465/how-to-use-c-to-get-the-folder-directory-name-but-not-the-path-of-one-file-e) – Nicolas Dusart May 26 '20 at 10:16
  • I found that question (it's the one I linked) but I had already experimented with `.filename()`, found that it didn't seem to work for directories in `std::filesystem`, and assumed it was either a difference in behaviour between `std` and `boost` or working because that path had a file on the end. However, I'm not so sure now. – Withad May 26 '20 at 11:01

1 Answers1

21

You could obtain it using:

fake_path.parent_path().filename()
Nicolas Dusart
  • 1,867
  • 18
  • 26
  • 1
    Interesting. This works but I'm not sure I understand why. It seems like the parent_path result still has some connection to the original path (rather than just being equivalent to ""C:\\fake\\path\\to\\") but treats "my_directory" as a file? – Withad May 26 '20 at 11:04
  • 7
    `std::path` does not know if the path actually points to an actual directory or a file. It may even contain an non existent path. It is basically a list of identifiers (representing each directory names, ending with a final identifier which could potentially represent a directory or a file). When there is a trailing (back)slash, the final identifier is an empty string. Calling `parent_path`, gives you a new path without the final element (here the empty string). – Nicolas Dusart May 26 '20 at 11:16
  • 1
    Ah, okay, that makes sense. There being an empty final identifier is the part I was missing, I think. – Withad May 26 '20 at 11:40