Search code examples
c++visual-studio-2017windows-api-code-pack

Why won't the FindFirstFile function accept my pointer to a data struct?


Dear Stack Overflow community.

I am a first time poster here. I've found this forum very helpful in the past and hope to contribute in many ways in the future. Right now I have a problem that I can't make out head or tail of.

I am trying to acquire the filenames in a specific directory using the FindFirstFileA, FindNextFileA and CloseFind functions. I'm writing C++ code in Microsoft Visual Studio 2017 and using UNICODE.

I opted for the "A"-suffix version rather than the "regular" one because I found working with LPCWSTR cumbersome.

My code for the relevant function looks like this at present:

void MainLoop::FindFiles(std::string Directory)
{
    Directory = Directory + "*";
    LPCSTR Path = Directory.c_str();
    LPWIN32_FIND_DATAA FileData;
    HANDLE hFind;
    hFind = FindFirstFileA(Path, FileData);
    while (FindNextFileA(hFind, FileData) != 0)
    {
        Files.push_back(FileData->cFileName);
    }
    FindClose(hFind);
}

There is one "weird" thing about this code, and one error which doesn't let me compile.

The "weird" thing:

In all of the documentation and examples I can find on all FindFirstFile functions it says that the second parameter should be a pointer and thus my code should actually look like this: hFind = FindFirstFileA(Path, &FileData); But when I try that, the compiler tells me that LPWIN32_FIND_DATAA* is not compatible with LPWIN32_FIND_DATAA. I don't know what's going on there, so some light on it would be appreciated.

The actual error does not concern this, however:

When I try to run the program, I'm given an error message stating that "FileData" is uninitialized and then refuses to run. In all examples I've seen, the data structure is declared just as I have. No forum posts I can find address my particular problems. Now, I know that I've only posted a specific function and if you need to know more of my setup I'll be glad to fill you in. Any insight into my problem or constructive comments on either my post or my code are welcome.

Respectfully

Niklas Björkeroth


Solution

  • This is an uninitialized pointer:

    LPWIN32_FIND_DATAA FileData;
    

    LPWIN32_FIND_DATAA is a typedef for WIN32_FIND_DATAA*.

    What you need is an actual instance of the structure, like

    WIN32_FIND_DATAA FileData;
    

    Notice that LP is gone from the beginning of the type.

    Then when you pass its address to the function, the pointer type will match.

    hFind = FindFirstFileA(Path, &FileData);