VC文件目录常见操作实例汇总(2)
#include <tchar.h>
#include <list>
#include <set>
#include <cassert>
#include <string>
typedef std::basic_string<TCHAR> _tstring; //宽字符串
typedef std::list<_tstring> _tslist; //字符串链表
/*
返回文件名的链表。
filepath 目录的完整路径,不带//
filefilterlist 文件扩展名列表,可以是多种类型的组合,比如说.txt;.xls;.doc
isordered 是否对文件名排序
*/
_tslist SearchFile(LPCTSTR filepath, LPCTSTR filefilterlist = _T(".*" ), bool isordered = true)
{
assert(filepath != NULL);
TCHAR buffer[MAX_PATH];
#if _MSC_VER > 1310
/* 1310 for Microsoft Visual C++ .NET 2003. 1310 represents /version 13 and a 1.0 point release. The Visual C++ 2005 compiler version is 1400, the number.
*/
_tcscpy_s(buffer, filepath); //_tcscpy_s is a micro for strcpy_s and strwcpy_s
#else
_tcscpy(buffer,filepath); //
#endif
_tslist filenamelist; // initial length is 100
WIN32_FIND_DATA finddata;
HANDLE searchhandle = INVALID_HANDLE_VALUE;
size_t length= _tcslen(filepath);
if (buffer[length-1] != _T('//'))
{
_tcscat_s(buffer,_T("//*")); // 向字符串结尾添加/*, 用来查找所有文件
}
if ( (searchhandle = ::FindFirstFile(buffer, &finddata)) != INVALID_HANDLE_VALUE )
{
while (::FindNextFile(searchhandle, &finddata) != 0)
{
if ( !(finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) // 为文件
{
if ( !_tcsicmp(filefilterlist, _T(".*"))) // 将所有文件输出到链表
filenamelist.push_back(finddata.cFileName);
else
{
//get file filter list string, a example, file filter may be ".txt;.xls;.doc"
_tstring filterstring = filefilterlist;
_tstring filename(finddata.cFileName);
_tstring::size_type index = filename.find_last_of(_T('.'));
if (index == _tstring::npos) // 文件没有扩展名,跳过
continue;
else
{
_tstring extname = filename.substr(index+1); //取得文件的扩展名
_tstring::size_type exist;
exist = filterstring.find(extname);
if (exist != _tstring::npos) //判断文件的扩展名是否在扩展名列表里
filenamelist.push_back(finddata.cFileName);
}
}
}
}
}
::FindClose( searchhandle );