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
Run Code Online (Sandbox Code Playgroud)
这是我使用的方法。它对我有用,但看起来很难看。所以我更喜欢寻找 boost::filesystems 或其他优雅的代码。注意:这个问题不重复,与提出的问题Get a directory name from a filename略有不同 。我的兴趣是找到文件名而不是整个目录路径。