Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 329
Withad Avatar asked May 26 '20 09:05

Withad


People also ask

What is boost :: filesystem :: path?

boost::filesystem::path is the central class in Boost. Filesystem for representing and processing paths. Definitions can be found in the namespace boost::filesystem and in the header file boost/filesystem. hpp . Paths can be built by passing a string to the constructor of boost::filesystem::path (see Example 35.1).


1 Answers

You could obtain it using:

fake_path.parent_path().filename()
like image 164
Nicolas Dusart Avatar answered Oct 17 '22 12:10

Nicolas Dusart