用C++遍歷一個文件夾下面所有的文件 Zz
//
#include <algorithm>
using namespace std;
// 使用UNICODE字符集
// 如果不使用Unicode可以解鎖下面的:
#include <windows.h>
#include <string>
// 版本控制
#include <tchar.h>
// 提供字符串的定義有中文的時候最好使用wstring
typedef std::wstring String;
#else
typedef std::string String;
#endif
// 定義文件名的定義
// 查找當前目錄下的所有文件返回所有文件的文件名請以FilesVec的引用的方式傳遞
// pathName 爲路徑名
_tcscpy_s( PathBuffer,_MAX_PATH, pathName );
FindClose( hFind );
{
FilesVec files;
try
{
FindFiles( _T("C://Program Files//") , files );
}
catch( exception &e )
{
cout<<"查找過程中發生了異常"<<endl;
cout<<e.what()<<endl;
return -1;
}
locale loc("chs");
wcout.imbue( loc );
copy( files.begin(), files.end(), ostream_iterator< String,TCHAR >( wcout, _T("/n") ) );
#else
copy( files.begin(), files.end(), ostream_iterator< String,TCHAR >( cout, _T("/n") ) );
#endif
system("pause");
return 0;
}
1、簡介
文件查找在很多場合會被派上用場,類ffsco將文件查找操作簡單封裝,使用只需要傳遞參數查找路徑和文件匹配格式(可以繼承該類的 match 方法實現自己的匹配算法)到find方法,查詢結果(文件/目錄等)被保存到類內部的vector容器,以後想怎麼用都行。
要求:
2、說明
使用WIN32提供的函數FindFirstFile/FindNextFile實現。子目錄查找用遞歸方法。 3、使用方法
將文件ffsco.h/ffsco.cpp加入,在使用的地方包含文件ffsco.h,e.g.
#include "ffsco.h"
加入名字空間使用聲明:
using namespace helper_coffs;
定義ffsco類對象:
ffsco o;
設置是否查找子目錄:
//o.dirs(1); //--查找子目錄
設置查找結果個數上限(默認65536/最大1048576當然可以自己修改限制):
//o.limit(100); //--最多查找100個
開始查找(返回結果個數):
int count = o.find(path, fext); //int count = o.find("c://winnt"); //int count = o.find("c://winnt", "*.exe; *.dll; *.ini"); //int count = o.find("c://winnt//", "*.exe; *.dll; *.ini");
取結果:
ffsco::typeT coo; coo = o.co(); //--文件目錄混合 coo = o.co_dir(); //--全部目錄 coo = o.co_file(); //--全部文件
使用結果:
for (ffsco::typeT::iterator it = coo.begin(); coo.end() != it; it ++) { cout << *it << endl; //想怎麼用??? }
就是這麼簡單:)
更多使用請參考ffsco類提供的test()...