非递归遍历目录在遍历windows等目录的情况下还是很必要的。昨天刚好需要,就写了个。需求是遍历目录生成索引,根据参数指定,是否索引目录,可以指定需要索引的文件类型。
用到的结构体和容器定义,就是个意思,具体就根据需求再定
<textarea cols="50" rows="15" name="code" class="cpp">struct LOCAL_APP_INDEX_ITEM { std::wstring name; std::wstring fullPath; LOCAL_APP_INDEX_ITEM() { name = L""; fullPath = L""; } LOCAL_APP_INDEX_ITEM(const LOCAL_APP_INDEX_ITEM& res) { name = res.name; fullPath = res.fullPath; } LOCAL_APP_INDEX_ITEM& operator=(const LOCAL_APP_INDEX_ITEM& res) { name = res.name; fullPath = res.fullPath; return *this; } }; typedef vector< LOCAL_APP_INDEX_ITEM > LOCAL_APP_INDEX_VEC; </textarea>
遍历过滤文件类型用的函数,支持"*.*"或者"*.lnk,*.url,*.exe"
<textarea cols="50" rows="15" name="code" class="cpp">BOOL _MatchFilterType(const wstring fileName, const wstring types) { size_t pos = wstring::npos; pos = types.find(L"*.*"); if (pos != wstring::npos) return TRUE; pos = fileName.rfind(L"."); if (wstring::npos != pos) { wstring fileType = fileName.substr(pos, fileName.size()); pos = types.find(fileType); if (wstring::npos != pos) return TRUE; else return FALSE; } return FALSE; }</textarea>
遍历的函数
<textarea cols="50" rows="15" name="code" class="cpp">BOOL _GenerateIndexFromDir( const wstring path, const BOOL indexDirs, const wstring types, LOCAL_APP_INDEX_VEC& localAppIndexs) { BOOL bRet = FALSE; WIN32_FIND_DATA findData; typedef std::queue< wstring > ENUM_DIR_QUEUE; ENUM_DIR_QUEUE dirQueue; dirQueue.push(path); while (!dirQueue.empty()) { wstring strCurDir = dirQueue.front(); wstring strIndex; dirQueue.pop(); ////////////////////////////////////////////////////////////////////////// HANDLE hFind = FindFirstFile((strCurDir + L"//*.*").c_str(), &findData); if (INVALID_HANDLE_VALUE != hFind) { do { if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if ((wcscmp(findData.cFileName, L".") != 0) && (wcscmp(findData.cFileName, L"..") != 0)) { LOCAL_APP_INDEX_ITEM item; item.name = findData.cFileName; item.fullPath = (strCurDir + L"//") + findData.cFileName; if (indexDirs) localAppIndexs.push_back(item); dirQueue.push(item.fullPath); } continue; } LOCAL_APP_INDEX_ITEM item; item.name = findData.cFileName; item.fullPath = (strCurDir + L"//") + findData.cFileName; if (_MatchFilterType(findData.cFileName, types)) localAppIndexs.push_back(item); } while(FindNextFile(hFind, &findData)); FindClose(hFind); } ////////////////////////////////////////////////////////////////////////// } return bRet; }</textarea>
没有注释,实在很抱歉
--- the end ---