使用boost中的filesystem类库遍历某个目录所有的文件

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

使用boost中的filesystem类库遍历某个目录所有的文件
int GetAllFileOfPath(const string strPath)
{
namespace fs = boost::filesystem;

 // 得到配置文件夹.
 if ( strPath.size() < 2 )
 {
  return 0;
 }
 fs::path full_path( fs::initial_path() );
 full_path = fs::system_complete( fs::path( strPath, fs::native ) );

 unsigned long file_count = 0;
 unsigned long dir_count = 0;
 unsigned long err_count = 0;

 if ( !fs::exists( full_path ) )
 {
  std::cout << "找不到配置文件目录,请检查该目录是否存在:"
  std::cout << full_path.native_file_string() << std::endl;

  return -1;
 }

 // 遍历配置文件所在的文件夹,得到所有的配置文件名.
 if ( fs::is_directory( full_path ) )
 {
  fs::directory_iterator end_iter;
  for ( fs::directory_iterator dir_itr( full_path );
     dir_itr != end_iter;
     ++dir_itr )
  {
    try
    {
   if ( fs::is_directory( *dir_itr ) )
   {
     string strSubDir(full_path.native_directory_string()) ;
     strSubDir.append("//");
     strSubDir.append(dir_itr->leaf());
     // 如果有子目录,则递归遍历.
     GetAllFileOfPath(strSubDir);
   }
   else
   {
    // 先组成包括完整路径的文件名
    string strFileName(full_path.native_directory_string());
    strFileName.append("//");
    strFileName.append(dir_itr->leaf());

    fs::path full_file( fs::initial_path() );
    full_file = fs::system_complete(fs::path(strFileName, fs::native));
    
    //加载解析文件中的信息.
    //do something;
   }
    }
    catch ( const std::exception & ex )
    {
   ++err_count;
   string strMsg = dir_itr->leaf();
   strMsg.append(",出现错误:");
   strMsg.append(ex.what());

   std::cout << strMsg.c_str() << std::endl;
    }
  }//<--for()
 }
 else // must be a file
 { 
  string strMsg = full_path.native_file_string();
  strMsg.append(",不是文件目录.");

  std::cout << strMsg.c_str() << std::endl;  
  return -1;
 }

 return err_count;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值