c++windowswinapidirectory-listing

How to list files in a directory using the Windows API?


I have this code and it displays the folder with the directory itself and not its contents. I want to display its contents. I don't want to use boost::filesystem.

How can I resolve this?

Code:

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

int main()
{
    WIN32_FIND_DATA data;
    HANDLE hFind = FindFirstFile("C:\\semester2", &data);      // DIRECTORY

    if ( hFind != INVALID_HANDLE_VALUE ) {
        do {
            std::cout << data.cFileName << std::endl;
        } while (FindNextFile(hFind, &data));
        FindClose(hFind);
    }
}

Output:

semester2

Solution

  • HANDLE hFind = FindFirstFile("C:\\semester2", &data);       // DIRECTORY
    

    You got the directory because that's what you asked for. If you want the files, ask for them:

    HANDLE hFind = FindFirstFile("C:\\semester2\\*", &data);  // FILES
    

    (You can instead use *.* if you prefer, but apparently this only works because of a backwards compatibility hack so should probably be avoided. See comments and RbMm's answer.)