Search code examples
cfiledirectoryenumerate

Enumerate files in directory with wildcard in C


I use code like this to enumerate all shader files in subdirectory shaders:

HANDLE hFind;
WIN32_FIND_DATA FindFileData;
shader_counter = 1;
pclog("searching shader files \n");
hFind = FindFirstFile("shaders\\*.fx", &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
    pclog("no shader files found \n");
}
else
{
    pclog("shader files found \n");
    while(hFind!=INVALID_HANDLE_VALUE)
    {
          pclog("Filename=%s\n",FindFileData.cFileName);
          hFind = FindNextFile(hFind, &FindFileData);
          shader_counter++;
    }
    pclog("Exit loop\n");
    FindClose(hFind);
    hFind = INVALID_HANDLE_VALUE;
}

But it only outputs 3 files out of many and crashes. What am I doing wrong ?

Edit , this is correct code to enumerate subdirectory using wildcard , maybe someone will find it usefull:

HANDLE hFind;
WIN32_FIND_DATA FindFileData;
BOOL found = TRUE;
hFind = FindFirstFile("shaders\\*.fx", &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{ // directory/wildcard not found 
}
else
{
    while(found)
    {
          //printf("Filename=%s\n",FindFileData.cFileName);
          found = FindNextFile(hFind, &FindFileData);
    }
    FindClose(hFind);
    hFind = INVALID_HANDLE_VALUE;
}

Solution

  • According to the Microsoft documentation, the return value to FindNextFile is not the same as for FindFirstFile. FindNextFile returns a boolean value:

        ...
        BOOL found = TRUE;
        printf("shader files found \n");
        while (found)
        {
              printf("Filename=%s\n",FindFileData.cFileName);
              found = FindNextFile(hFind, &FindFileData);
              shader_counter++;
        }
        printf("Exit loop\n");
        FindClose(hFind);
        ...
    

    (It has to be an independent value, otherwise you would pass an invalid handle to FindClose.)