Skip to content

Recursive Directory Scan

A C++ function that recursively walks a directory tree with FindFirstFile/FindNextFile, printing every file it finds.

Published Sep 21, 2000

The classic recursive directory walk in about forty lines. ProcessFiles builds a path\*.* pattern, iterates the entries with FindFirstFile/FindNextFile, skips the . and .. pseudo-entries, recurses into anything with FILE_ATTRIBUTE_DIRECTORY, and prints everything else. It is the shape you want whenever you need to enumerate a whole tree - index files, copy, delete, or hash a folder - and it shows the one easy-to-forget detail: close the find handle before returning from the recursive branch so you do not leak handles on deep trees.

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool ProcessFiles(const char *sPath)
{
	WIN32_FIND_DATA fdFile;
	HANDLE hFind = NULL;

	char sTemp[2048];
	sprintf_s(sTemp, sizeof(sTemp), "%s\\*.*", sPath);

	if((hFind = FindFirstFile(sTemp, &fdFile)) == INVALID_HANDLE_VALUE)
	{
		printf("Path not found: [%s]\n", sPath);
		return false;
	}

	do
	{
		if(strcmp(fdFile.cFileName, ".") != 0 && strcmp(fdFile.cFileName, "..") != 0)
		{
			sprintf_s(sTemp, sizeof(sTemp), "%s\\%s", sPath, fdFile.cFileName);
			if(fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				if(!ProcessFiles(sTemp))
				{
					FindClose(hFind);
					return false;
				}
			}
			else{
				printf("%s\n", sTemp);
			}
		}
	}
	while(FindNextFile(hFind, &fdFile));

	FindClose(hFind);

	return true;
}

Call it once with your root path, e.g. ProcessFiles("C:\\Data"). For very large trees consider the wide-character FindFirstFileW variant (long-path safety) or SHFileEnum/IFileFinder if you want the shell's virtual-folder behavior for free.

An unhandled error has occurred. Reload 🗙