使用boost库编写跨平台遍历文件夹下的所有文件

来源:互联网 发布:javascript正则表达式= 编辑:程序博客网 时间:2024/06/02 06:51

#include "boost/filesystem.hpp"
#include <sstream>

bool getFiles( std::string path,std::vector<std::string> &vFiles )

{
using namespace boost::filesystem;
typedef recursive_directory_iterator  rd_iterator;
rd_iterator end;
for (rd_iterator pos(path.c_str());pos != end;++pos)
{
if (is_directory(*pos))
{
pos.no_push();
}
std::stringstream streamItem;
streamItem << *pos;
std::string sFileName;
streamItem>>sFileName;
vFiles.push_back(sFileName);
}
return true;

}

这个版本有个Bug,就是文件名中存在空格的时候读取的文件名被截断,正确的做法如下,

bool getDirFiles( std::string sDirName,std::vector<std::string> &vFiles)
{
fs::path fullpath (sDirName);

if(!fs::exists(fullpath)){return false;}
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
{
//ret.push_back(iter->path().string());
//std::cout << *iter << " is a file" << std::endl;
std::string sFileName = iter->path().string();
vFiles.push_back(sFileName);
}
} catch ( const std::exception & ex ){
std::cerr << ex.what() << std::endl;
continue;
}
}
return true;
}