最近整理項目發現一個曾經找了好久的有用的代碼片段,就是獲取文件夾下所有文件的名字,和當前文件的絕對路徑。
記錄一下。
使用的是boost庫,
#include <boost/filesystem.hpp> void getFiles(const string& rootPath,vector<string> &ret,vector<string> &name) { namespace fs = boost::filesystem; fs::path fullpath (rootPath); fs::recursive_directory_iterator end_iter; for(fs::recursive_directory_iterator iter(fullpath);iter!=end_iter;iter++) { try { if (fs::is_directory( *iter ) ) { std::cout<<*iter << "is dir" << std::endl; ret.push_back(iter->path().string()); } else { string file = iter->path().string(); ret.push_back(iter->path().string()); fs::path filePath(file); name.push_back(filePath.stem().string()); } } catch ( const std::exception & ex ) { std::cerr << ex.what() << std::endl; continue; } } } void testLocal(string imgPath) { vector<string> nameWithPath;//絕對路徑 vector<string> imgName;//文件名字 //get files getFiles(imgPath, nameWithPath, imgName); for(int i = 0; i < nameWithPath.size(); i++) { Mat image = imread(nameWithPath[i]); //do something cout<<imgName[i]<<" "<<endl; } delete detModel; }
需要依賴的庫是