读取文件夹下指定类型的文件(windows)

C++读取目录下特定文件
本文提供了一个使用C++编程语言实现的功能,能够帮助开发者读取指定目录下所有具有特定扩展名的文件,并将文件路径存储到一个字符串向量中。此代码适用于Windows平台,并展示了如何利用_findfirst和_findnext函数来枚举目录中的文件。

转自http://blog.youkuaiyun.com/carson2005/article/details/26452699

直接上代码

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. #ifdef WIN32  
  5. #include <io.h>  
  6. #else  
  7. #endif  
  8.   
  9. void ReadDirectory( const string& directoryName, const string fileExt, vector<string>& filenames, bool addDirectoryName=true )  
  10. {  
  11.     filenames.clear();  
  12.   
  13. #ifdef WIN32  
  14.     struct _finddata_t s_file;  
  15.     string str = directoryName + "\\*" + fileExt;  
  16.   
  17.     intptr_t h_file = _findfirst( str.c_str(), &s_file );  
  18.     if( h_file != static_cast<intptr_t>(-1.0) )  
  19.     {  
  20.         do  
  21.         {  
  22.             if( addDirectoryName )  
  23.                 filenames.push_back(directoryName + "\\" + s_file.name);  
  24.             else  
  25.                 filenames.push_back((string)s_file.name);  
  26.         }  
  27.         while( _findnext( h_file, &s_file ) == 0 );  
  28.     }  
  29.     _findclose( h_file );  
  30. #else  
  31.       
  32. #endif  
  33.   
  34.     sort( filenames.begin(), filenames.end() );  
  35. }  
  36.   
  37. int main()  
  38. {  
  39.     vector<string> fileNames;  
  40.     ReadDirectory("C:\\Users\\Administrator\\Desktop\\新建文件夹"".png", fileNames);  
  41.     for (int i=0; i<fileNames.size(); i++)  
  42.     {  
  43.         printf("%s \n", fileNames[i].c_str());  
  44.     }  
  45.     printf("ok \n");  
  46.   
  47.     system("pause");  
  48.     return 0;  
  49. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值