Question

I'm trying to show files of a directory recursively but I'm getting a stack overflow error(I'm new to win32API):

Unhandled exception at 0x77aa1f38 in xxx.exe: 0xC00000FD: Stack overflow.

How do I solve that?

#include <windows.h>
#include <tchar.h> 
#include <stdio.h>
#include <strsafe.h>
#include <assert.h>
#include <string.h>

void getAllFiles(TCHAR *target_dir);

int _tmain(int argc, _TCHAR* argv[])
{
    getAllFiles(TEXT(".\\*"));
    getchar();
}

void getAllFiles(TCHAR *target_dir)
{
    WIN32_FIND_DATA ffd;
    TCHAR szDir[MAX_PATH] = {0};
    HANDLE hFind = INVALID_HANDLE_VALUE;
    DWORD dwError = 0;

    StringCchCopy(szDir, MAX_PATH, target_dir);
    hFind = FindFirstFile(szDir, &ffd);

    if(hFind == INVALID_HANDLE_VALUE)
    {
        printf("FindFirstFile");
        return;
    }

    do
    {

            if(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if(_tccmp(ffd.cFileName, TEXT(".")) && _tccmp(ffd.cFileName, TEXT("..")))
                {
                    getAllFiles(ffd.cFileName);
                }
            }
            else
            {
                _tprintf(TEXT("%s\n"), ffd.cFileName);
            }

   }
   while (FindNextFile(hFind, &ffd) != 0);

   dwError = GetLastError();
   if (dwError != ERROR_NO_MORE_FILES) 
   {
      printf("FindFirstFile\n");
   }
    FindClose(hFind);
 }
Was it helpful?

Solution

You first pass a directory name to be searched recursively. Now for all subdirectories, you skip . and .. and pass remaining directory name recursively to this function.

You never add \* to this directory name to make it a patter to seach recursively, which makes FindFirstFile to return this directory itself. (As the directory is the only one that mathes without pattern.) and hence the infinite recursion and stack overflow.

Solution You should append \* to to the directory name before calling you getAllFiles function recursively.

OTHER TIPS

You only test the FindFirstFile return value for INVALID_HANDLE_VALUE. It may also return ERROR_FILE_NOT_FOUND.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top