Search code examples
c++boost-filesystem

how to use C++ to get the folder/directory name, but not the path of one file? Especially boost::filesystem;


    std::string file="C:\\folder1\\folder2\\folder3.txt";
fs::path file_path(file);
fs::path file_dir=file_path.parent_path();// "C:\\folder1\\folder2";
std::string str_path=file_path.string();
std::string str_dir=file_dir.string();
std:string str_folder=str_path.erase(0,str_dir()+1);// return folder2

This is the method I used. It works for me, but it looks ugly. So I prefer to look for boost::filesystems or other elegant code. Notes: THis question is not duplicated and sligtly different from the question proposed Getting a directory name from a filename. My interest is to find the filename but not the whole directory path.


Solution

  • You can use parent_path to get rid of the last element in the path, then filename to get the last element. Example: include boost/filesystem.hpp and iostream

    namespace fs = boost::filesystem;
    int main()
    {
       fs::path p ("/usr/include/test");
       std::cout << p.parent_path().filename() << "\n";
    }
    

    should print "include".