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);
}
}
}
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
*.txtwildcard. It may be easier to do the wildcard testing yourself.So change the code to:
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
FindNextFileto the end of the loop.