I believe the experimental
version of std::filesystem
was already available in C++14.
If it is indeed available in your environment, you can use parent_path()
to get the parent folder from a path
. Then you can use the method filename()
to extract the name without the full path specification.
In order to convert a path
to std::string
you can use the string()
method.
#include <string>
#include <iostream>
#include <experimental/filesystem>
int main(int argc, char const* argv[])
{
std::string path_str = "/home/abc/fi.mp4";
std::experimental::filesystem::path p = path_str;
std::experimental::filesystem::path parent_p = p.parent_path();
std::experimental::filesystem::path parent_p_fname = p.parent_path().filename();
std::string result_str = parent_p_fname.string();
std::cout << result_str << std::endl;
return 0;
}
Output:
abc
You can further use parent_path()
to climb up the hirarchy.
Once C++17 is available for you, you can simply drop the experimental
prefix.