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
这就是我用的方法。对我来说很管用,但看起来很难看。因此,我更愿意寻找boost::filesystems或其他优雅的代码。注: THis问题与提议的Getting a directory name from a filename问题并没有重复和巧妙的不同。我感兴趣的是找到文件名,而不是整个目录路径。
发布于 2016-09-01 07:50:32
您可以使用parent_path
消除路径中的最后一个元素,然后使用filename
获取最后一个元素。示例:包括boost/boost ystem.hpp和iostream
namespace fs = boost::filesystem;
int main()
{
fs::path p ("/usr/include/test");
std::cout << p.parent_path().filename() << "\n";
}
应该打印“包括”。
发布于 2016-09-01 07:48:25
这个问题是在另一堆帖子中提出的。Boost filesystem
在你的情况下,你可以做这样的事情。
boost::filesystem::path p("C:\\folder1\\folder2\\folder3.txt"); boost::filesystem::path dir = p.parent_path();
https://stackoverflow.com/questions/39275465
复制相似问题