Win32 API : Stack overflow in recursive file search function in C

0

I'm trying to make a program that is supposed to :

  • Search for a specific file by going into a directory and its subdirectories (recursively)

But I kinda messed up, I have a stack overflow. Here's the function that causes me troubles:

BOOL LoopThroughDirectories(LPTSTR fileName)
{
    //Searching for files that matches in the current directory
    WIN32_FIND_DATA ffd;
    HANDLE hFirstFile = FindFirstFile(fileName, &ffd);

    if (hFirstFile != INVALID_HANDLE_VALUE)
    {
        do
        {
            //If it's not a directory
            if (ffd.dwFileAttributes & FILE_ATTRIBUTE_NORMAL)
            {
                _tprintf("%s\n", ffd.cFileName);
            }
        } while (FindNextFile(hFirstFile, &ffd));
    }

    FindClose(hFirstFile);

    //Go into the first unexplored directory
    HANDLE hFirstDir = FindFirstFile(_T("*"), &ffd);

    if (hFirstDir != INVALID_HANDLE_VALUE)
    {
        do
        {
            //If it's a directory
            if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                //Go into it 
                SetCurrentDirectory(ffd.cFileName);
                //and do the same
                LoopThroughDirectories(fileName);
                SetCurrentDirectory(_T(".."));
            }
        } while (FindNextFile(hFirstDir, &ffd));
    }
    FindClose(hFirstDir);
    return TRUE;
}

Here's my main function:

int _tmain(int argc, LPCTSTR argv[])
{
    //Parsing the command line arguments

    //Processing the fileName
    LPTSTR tempPath;
    LPTSTR fileName;

    //Checking for emptyness
    if (argc == 2)
    {
        tempPath = argv[1];
    }

    else
    {
        //If empty set filename to *
        tempPath = _T("*");
    }

    //Removing trailing backslash if any
    LPTSTR backSlash = _tcsrchr(tempPath, _T("\\"));

    if (backSlash != NULL)
    {
        //Replacing backslash with terminating null character
        *backSlash = _T("\0");
    }

    fileName = tempPath;

    //Looping through directories
    LoopThroughDirectories(fileName);

    return EXIT_SUCCESS;
}

Here's the exception that the VS Debugger gave me (I speak French sorry):

Exception non gérée à 0x77382358 (ntdll.dll) dans lsW.exe : 0xC00000FD: Stack overflow (paramètres : 0x00000001, 0x00802FEC).

c
recursion
winapi
asked on Stack Overflow Apr 5, 2020 by (unknown user)

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0