FindFirstFile Not working with Wild cards
I am trying to use the FindFirstFile
function to traverse through all of my .txt
files, but I am getting INVALID_VALUE_HANDLE
error when I try it, here is my function:
int search(LPSTR lpszPath)
{
WIN32_FIND_DATA WFD;
HANDLE hSearch;
CHAR szFilePath[MAX_PATH + 1];
PathCombine(szFilePath, lpszPath, "*.txt");
hSearch = FindFirstFile(szFilePath,&WFD);
if(hSearch == INVALID_HANDLE_VALUE)
{
printf("Error Handle Value\n");
}
while (FindNextFile(hSearch,&WFD))
{
if(strcmp(WFD.cFileName,"..") && strcmp(WFD.cFileName,"."))
{
if(WFD.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
PathCombine(szFilePath, lpszPath, WFD.cFileName);
search(szFilePath);
}
else
{
PathCombine(szFilePath, lpszPath, WFD.cFileName);
printf("%s\n",szFilePath开发者_如何学Go);
}
}
}
FindClose(hSearch);
return 0;
I think the problem comes from the wildcard, any suggestions?
I imagine that the problem is that this will only find objects that match *.txt
. You are wanting a recursive search that descends into directories. But it will only descend into directories that match *.txt
.
For a recursive search like this you have to enumerate all the directories without the *.txt
wildcard. It may be easier to do the wildcard testing yourself.
So change the code to:
PathCombine(szFilePath, lpszPath, "*");
and test each file individually for the extension .txt
.
As others have pointed out, you are failing to check the first file that is found. You must move the FindNextFile
to the end of the loop.
CORRECTION: sorry i used it only in the unicode version. So David is right it works with ANSI characters as well. In this case my guess is, that the path you concatenating is not valid. Maybe you didn't escape the backslash properly e.g. "c:\test\*.txt"
the problem is not the wildcards but the wrong character type. In order to something like this you need to use wide character strings.
look at MSDN for an example
So you call FindFirstFile
and without processing the result you are calling FindNextFile
again for next file? I am sure you wanted this first result too.
精彩评论