用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()...