今天看到以前的一些代码,觉得比较常用,放在下面供初学者使用吧。下面的代码都采用VS2002编译测试通过。参数dir是查找的根目录,filename为要查找的文件名(区分大小写), 第三个参数为找到后返回找到的文件路径,传入TCHAR resultPath[MAX_PATH];类型。
- /**
- * 1. 采用Win32 API: FindFirstFile() 和 WIN32_FIND_DATA
- */
- HRESULT AcadDocProcessor::FindFile(LPCTSTR dir, LPCTSTR filename, LPTSTR resultPath)
- {
- HRESULT hr = E_FAIL;
- TCHAR tmpDirExpr[MAX_PATH];
- memset(tmpDirExpr, 0, MAX_PATH * sizeof(TCHAR));
- strcat(tmpDirExpr, dir);
- strcat(tmpDirExpr,_T("//*"));
- WIN32_FIND_DATA FindFileData;
- HANDLE hFind=::FindFirstFile(tmpDirExpr,&FindFileData);
- if(INVALID_HANDLE_VALUE == hFind)
- return hr;
- while(TRUE)
- {
- if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
- {
- if(FindFileData.cFileName[0]!='.')
- {
- TCHAR szFile[MAX_PATH];
- strcpy(szFile, dir);
- strcat(szFile, "//");
- strcat(szFile, FindFileData.cFileName);
- hr = FindFile(szFile, filename, resultPath);
- if(SUCCEEDED(hr))
- break;
- }
- }
- else
- {
- if(strcmp(FindFileData.cFileName, filename) == 0)
- {
- strcpy(resultPath, dir);
- strcat(resultPath, "//");
- strcat(resultPath, FindFileData.cFileName);
- //DWORD len = strlen(FindFileData.cFileName) * sizeof(TCHAR) + 1;
- //memcpy(resultPath, FindFileData.cFileName, len);
- hr = S_OK;
- break;
- }
- }
- if(!FindNextFile(hFind,&FindFileData))
- break;
- }
- FindClose(hFind);
- return hr;
- }
-
- 2.:以下是使用CFindFile类的实现:(注意在delete目录的时候需要调用CFindFile类的close函数否则会导致,句柄没有释放无法删除目录)
- 以下是使用CFindFile类的实现
BOOL SearchFile(CString cstrSourceDir, CString cstrFileName, CString &cstrOutFilePath)
{
//判断传入的文件夹路径是否有'/'
DWORD dwLen = cstrSourceDir.GetLength();
TCHAR ch = cstrSourceDir.GetAt(dwLen-1);
if (ch != '\\')
{
cstrSourceDir = cstrSourceDir + _T("\\");
}
//判断文件是否存在
if ( !PathFileExists(cstrSourceDir))
{
return FALSE;
}
BOOL bResult = FALSE;
CString cstrFindFile = cstrSourceDir + _T("*.*");
CFileFind cFileFind;
BOOL bFind = FALSE;
bFind = cFileFind.FindFile(cstrFindFile,0);
while(bFind)
{
bFind = cFileFind.FindNextFile();
if ( !cFileFind.IsDots())
{
if (cFileFind.IsDirectory())
{
CString cstrSubPath = cFileFind.GetFilePath();
if ( SearchFile(cstrSubPath, cstrFileName, cstrOutFilePath))
{
bResult = TRUE;
break;
}
}
else
{
CString cstrTmpFileName = cFileFind.GetFileName();
if (0 == cstrTmpFileName.CompareNoCase(cstrFileName))
{
//查找成功返回输出路径
cstrOutFilePath = cFileFind.GetFilePath();
bResult = TRUE;
break;
}
}
}
};
//使用完需要关机文件句柄
- cFindFile.close();
return bResult;
}