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

1

14

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?

Overpass answered 26/5, 2020 at 9:16 Comment(2)
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;Burch
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.Overpass
B
23

You could obtain it using:

fake_path.parent_path().filename()
Burch answered 26/5, 2020 at 9:21 Comment(3)
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?Overpass
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).Burch
Ah, okay, that makes sense. There being an empty final identifier is the part I was missing, I think.Overpass

© 2022 - 2024 — McMap. All rights reserved.