By Brandon W. Yuille
I want to share a function that is very useful when dealing with file operations and management. The following function (void EnumDirFiles(...)), can be used as is to simply list all the files within a directory and all the files within the subdirectories of the directory. The usages for such a function are vast, as this is a basis for all file enumeration operations.
I hope you will find this as useful as I do!
Implementation
int main()
{
EnumDirFiles("C:\\Program Files"); // List all files within the Program Files directory.
return 0;
}
Recursive Function Definition
void EnumDirFiles(char *lpszDir)
{
HANDLE hDir;
BOOL bDone = FALSE;
WIN32_FIND_DATA FileData;
char szFind[512];
strcpy(szFind, lpszDir);
strcat(szFind, "\\*");
hDir = FindFirstFile(szFind, &FileData);
if(hDir == INVALID_HANDLE_VALUE)
{
printf("Invalid Directory: \"%s\"\n", lpszDir);
return;
}
while(!bDone)
{
if(FileData.cFileName[0] != '.') // Exclude "." and ".."
{
char szFullFile[512];
strcpy(szFullFile, lpszDir);
strcat(szFullFile, "\\");
strcat(szFullFile, FileData.cFileName);
if(FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
printf("- Listing Directory: %s\n", szFullFile);
EnumDirFiles(szFullFile);
}
else
printf("%s\n", szFullFile);
}
if(!FindNextFile(hDir, &FileData))
{
if(GetLastError() == ERROR_NO_MORE_FILES)
{
bDone = TRUE;
}
else
{
printf("Unable to enumerate the next file.\n");
bDone = TRUE;
}
}
}
// Close the search handle.
FindClose(hDir);
}
