Recursive file listing by choosing a folder - C++ (Windows)

Submitted by sockfd on Wed, 07/10/2013 - 16:50

The code below shows how to simply loop recursively through a certain folder, picking up all subfolders and files. For the sake of simplicity, we do not do anything with those files.

You could print them out in the console - beware your app may hang! Or you could store them in a file or vector.

#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <iostream>

using namespace std;

void listDir(const char * dirn);

int main()
{
    listDir("C:\\Program Files\\");
    return 0;
}

void listDir(const char * dirn)
{
    char dirnPath[1024];
    sprintf(dirnPath, "%s\\*", dirn);

    WIN32_FIND_DATA f;
    HANDLE h = FindFirstFile(dirnPath, &f);

    if (h == INVALID_HANDLE_VALUE) { return; }

    do
    {
        const char * name = f.cFileName;

        if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) { continue; }

        char filePath[1024];
        sprintf(filePath, "%s%s%s", dirn, "\\", name);

        cout << filePath << endl;

        if (f.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
        {
            listDir(filePath);
        }

    } while (FindNextFile(h, &f));
    FindClose(h);
}