Jamie Keeling
Jamie Keeling

Reputation: 9966

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);
 }
}

Upvotes: 1

Views: 13408

Answers (2)

student0495
student0495

Reputation: 181

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

void main()
{
    HANDLE fileHandle;
    WIN32_FIND_DATA ffd;
    LARGE_INTEGER szDir;
    WIN32_FIND_DATA fileData;
    fileHandle = FindFirstFile("C:\\Users\\rest_of_the_Address\\*", &ffd);

    if (INVALID_HANDLE_VALUE == fileHandle)
        printf("Invalid File Handle Value \n");

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

You were missing some declarations, and had some syntax errors, fixed up here, and also, remember to check the msdn documentation (here is a msdn example for the program)

Upvotes: 0

interjay
interjay

Reputation: 110069

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);

Upvotes: 2

Related Questions