Article: C++ Windows File Recursion

13 December 2016

It's been a few years since I've worked on a video game and all the time I spent reversing games has re-sparked my interest in making my own. Unlike my Cake Quest game which was written in Java, I'll be writing this in C++ with Direct2D. After some simple project setup, my first obstacle was loading external images via the Windows Imaging Component (WIC) framework. Being familiar with writing level editors in the past, having a good file structure makes everything a lot easier especially if the project is large. Perhaps the simplest way to return a complete listing of files in a directory and its subdirectories is through recursion. There are many solutions including using the Boost libraries, but I took a pretty strict Windows approach.

So what we have is a pretty simple function under twenty lines, let's break it down starting with the constructor. First is the "FilePath" which is a given, the location where we want to start our recursive search. The second parameter is not required for the search, but it's a generic vector for storing results. For those that are unfamiliar with the ampersand ("&") next to the variable, it means we are performing a call by reference. We are directly accessing the vector which we pass into our constructor so we can update any vector that we specify.

ImageAsset is a custom class

FindFirstFile is the function which defines how we search for files and subsequent searching within the same directory is made using FindNextFile. The appended "\\*" to the file path means I'm searching for any file, however you can modify this to make it search for specific file types or names. Results are stored as WIN32_FIND_DATA which has a lot of useful properties. The property which we're most concerned with is the dwFileAttributes bit flags, specifically "FILE_ATTRIBUTE_DIRECTORY". If the file is a directory then recursively call the function, if not then we've found a "file". At this point I add my result as a generic object (the same object type as the referenced vector) using a pre-defined constructor. In this case, ImageAsset has a function for initializing that takes a file path in the constructor and loads the component as it's added.