hammackj

List Windows File System Recursively

In a few of the tools that I have written, I have needed to list the windows file system recursively. While .Net makes this much easier, all of the tools I write are in win32 C. Hopefully this will help someone else, as when I looked for information on this I did not find very much.

static void RecurseFileSystem(TCHAR *StartingPath)
{
    HANDLE CurrentFileHandle;
    WIN32_FIND_DATA FileInformation;
    TCHAR CurrentFileName[MAX_PATH];
    TCHAR m_szFolderInitialPath[MAX_PATH];
    TCHAR wildCard[MAX_PATH] = TEXT("\\*.*");

    _tcscpy_s(CurrentFileName, MAX_PATH, StartingPath);
    _tcscpy_s(m_szFolderInitialPath, MAX_PATH, StartingPath);
    _tcsncat_s(m_szFolderInitialPath, MAX_PATH, wildCard, MAX_PATH);

    CurrentFileHandle = FindFirstFile(m_szFolderInitialPath, &FileInformation);

    if(CurrentFileHandle != INVALID_HANDLE_VALUE)
    {
        do
        {
            if(
                (_tcscmp(FileInformation.cFileName, TEXT(".") ) != 0)
                &&
                (_tcscmp(FileInformation.cFileName, TEXT("..")) != 0))
            {
                _tcscpy_s(CurrentFileName, MAX_PATH, StartingPath);
                _tcsncat_s(CurrentFileName, MAX_PATH, TEXT("\\/**/"), MAX_PATH);
                _tcsncat_s(CurrentFileName, MAX_PATH, FileInformation.cFileName, MAX_PATH);

                if(FileInformation.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
                {
                    RecurseFileSystem(CurrentFileName);
                }
                else
                {
                    /* Do action on file here! */
                }
            }
        }
        while(FindNextFile(CurrentFileHandle, &FileInformation) == TRUE);

        FindClose(CurrentFileHandle);
    }
}