« Introduction to Call Capture | Main | Redirecting Console Input/Output using Pipes »

Recursively Enumerating the Files within a Directory and its Subdirectories

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);
}

TrackBack

TrackBack URL for this entry:
http://www.photontech.org/MT/mt-tb.cgi/4

About

This page contains a single entry from the blog posted on November 30, 2006 10:10 AM.

The previous post in this blog was Introduction to Call Capture.

The next post in this blog is Redirecting Console Input/Output using Pipes.

Many more can be found on the main index page or by looking through the archives.