Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    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.

like image 630
Pengju Zhao Avatar asked Sep 01 '16 15:09

Pengju Zhao


1 Answers

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".

like image 101
midor Avatar answered Sep 23 '22 03:09

midor