call "FindFileInDir(char* rootDir, char* extname, BOOL recursive)" in your code base, the function can filter folder path and file path
rootDir:search root directory (EX:"D:\\test\\")
extname:filename extension (EX:".exe")
recursive:the decide to search sub-directory or not (EX:"true")
EX1:FindFileInDir("D:\\test\\", ".exe", true); // to search every *.exe file under "D:\test\" directory
EX2:FindFileInDir("D:\\", "", false); // to search every file under "D:\" directory , but don't search in sub-directory
function:
void FindFileInDir(char* rootDir, char* extname, BOOL recursive)//, char* strRet)
{
char fname[1024];
ZeroMemory(fname, 1024);
WIN32_FIND_DATA fd;
ZeroMemory(&fd, sizeof(WIN32_FIND_DATA));
HANDLE hSearch;
char filePathName[256];
char tmpPath[256];
ZeroMemory(filePathName, 256);
ZeroMemory(tmpPath, 256);
strcpy(filePathName, rootDir);
char extFileName[256];
ZeroMemory(extFileName, 256);
strcpy(extFileName, extname);
BOOL bSearchFinished = FALSE;
if( filePathName[strlen(filePathName) -1] != '\\' )
{
strcat(filePathName, "\\");
}
strcat(filePathName, "*");
hSearch = FindFirstFile(filePathName, &fd);
//Is directory
if( (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") )
{
strcpy(tmpPath, rootDir);
strcat(tmpPath, fd.cFileName);
if( tmpPath[strlen(tmpPath) -1] != '\\' )
{
strcat(tmpPath, "\\");
}
if(recursive == true)
{
FindFileInDir(tmpPath, extFileName, recursive);
}
}
while( !bSearchFinished )
{
if( FindNextFile(hSearch, &fd) )
{
if( (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") )
{
strcpy(tmpPath, rootDir);
strcat(tmpPath, fd.cFileName);
if( tmpPath[strlen(tmpPath) -1] != '\\' )
{
strcat(tmpPath, "\\");
}
printf("Folder : %s\n", tmpPath); // show folder path
if(recursive == true)
{
FindFileInDir(tmpPath, extFileName, recursive);
}
}
else if( strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") )
{
if(strstr(fd.cFileName, extFileName))
{
printf("File : %s%s\n",rootDir,fd.cFileName); // show file path
}
}
}
else
{
if( GetLastError() == ERROR_NO_MORE_FILES )
{
bSearchFinished = TRUE;
}
else
{
bSearchFinished = TRUE;
}
}
}
FindClose(hSearch);
}
沒有留言:
張貼留言