/** * @file ListDirContent.cpp * @brief 对win32中有关列目录的API进行的简单封装 * @author 冷却 * @date 2010-8-15 */ #include <stdio.h> #include <windows.h> #include <vector> #include <string> using namespace std; /** * @brief 内容结构体 * @warning 这里所指的内容为:文件或目录 */ typedef struct _Content { string strName; /**< 内容的名称 */ int iAttr; /**< 内容的详细属性 */ bool fIsDir; /**< 内容是否是目录 */ } CONTENT; /** * @brief 列出指定目录内的所有内容(即:文件或目录) * @param[in] szDir 目录 * @param[in] strFilter 过滤器 * @param[out] rgContent 内容 * @return 成功:S_OK,失败:E_FAIL * @warning 列出来的内容已经去掉“.”和“..”这两个目录 */ HRESULT ListDirContent(char* szDir, const string& strFilter, vector<CONTENT>& rgContent) { if ( NULL == szDir || strlen(szDir)+strFilter.size() >= (MAX_PATH-1) ) { return E_FAIL; } char FileName[MAX_PATH]={0}; strcpy(FileName, szDir); strcat(FileName, "//"); strcat(FileName, strFilter.c_str()); CONTENT content; WIN32_FIND_DATA FindFileData; HANDLE hFind = FindFirstFile(FileName, &FindFileData); if ( hFind != INVALID_HANDLE_VALUE ) { do { content.strName = FindFileData.cFileName; content.iAttr = FindFileData.dwFileAttributes; content.fIsDir = (FILE_ATTRIBUTE_DIRECTORY == content.iAttr) ? true : false; if ( "." != content.strName && ".." != content.strName ) { rgContent.push_back(content); } } while ( FindNextFile(hFind, &FindFileData) ); FindClose(hFind); return S_OK; } else { return E_FAIL; } } //Demo int main(int argc, char** argv) { vector<CONTENT> v; ListDirContent(".//", "*.*", v); for ( int n=0; n<(int)v.size(); ++n ) { printf("%-16s%s/n", v[n].strName.c_str(), v[n].fIsDir ? "<DIR>" : ""); } getchar(); return 0; }