Jamie Keeling Jamie Keeling - 1 month ago 14
C Question

Find all files within directory using "FindFirstFileA" - C

I am using the Windows API and would like to be able to search through a specified directory and return the names of any files that reside within it.

I've made a start at it however i've hit a brick wall as i'm unsure of how to go any further.

Here is my progress so far:

#include <stdio.h>
#include <windows.h>

void main()
{
HANDLE fileHandle;
WIN32_FIND_DATAA fileData;

fileHandle = FindFirstFileA("*.txt", &fileData);

if(fileHandle != INVALID_HANDLE_VALUE)
{
printf("%s \n", fileData.cFileName);
}
}

Answer

You need to call FindNextFile in a loop to find all the files. There's a full example here, here are the interesting bits:

hFind = FindFirstFile(szDir, &ffd);

if (INVALID_HANDLE_VALUE == hFind) 
   return dwError;

do
{
   printf("%s\n"), ffd.cFileName);
}
while (FindNextFile(hFind, &ffd) != 0);