Introduction

Microsoft provided a sample code for Listing Files in a Directory, but that example code cannot be used to list files in the sub-directory, so how can we do that?

Enumerating/searching files and sub folders is in fact a rather basic skill, people have posted many articles on that, you can see the other examples here. However, many of those implementations enumerate files in a recursive way. As a beginner in programming, I just wonder how to do that non-recursively.

Recursive Implementation

In many cases, recursive implementation can be really elegant, if you already know how to do this recursively, then you may just simply skip this part.

To search files in Windows, we can use the APIs FindFirstFile/FindNextFile (or SHGetDataFromIDList, or the FileSystem library in boost), and a typical implementation is to do this recursively:

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 widecharacters, call the Unicode version of the function and prepend "\\?\" to the path.

Although some people said that 260 characters is good enough, and the stack might not that easily overflow, I guess avoiding recursion when possible can't be a bad idea; am I correct? This implementation is more like a practice for beginners like me, so let's just have fun coding it.

For those who still want to know how to implement this using DFS, you can dig into the demo code in this page and open the source file FileEnumerator.h, then you will see that I have prepared some #ifdef switch there, you can simply try comment out/uncomment this macros:

Using the Code

The initial design of classes was inspired by Andreas Saurwein Franci Gonçalves' article, please read his article first! Then you need to implement your own class derived from either CFileEnumeratorBase or CFilteredFileEnumerator.

CFileEnumeratorBase is provided for basic file enumeration, and CFilteredFileEnumerator is provided for pattern filtering enumeration.