Hack Forums
[C] Iterate over directories (non-recursive) - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C] Iterate over directories (non-recursive) (/showthread.php?tid=6101900)



Iterate over directories (non-recursive) - SIM-3437924 - Aug 11, 2020

Hi,

I'm trying to iterate over directories trees to search for any files in them. This can't be a function so recursing is not possible.

Best example of what i'm trying to do below. It works perfectly, except it is a recusive function so it's no use to me.

Code
void WINAPI SearchFile(PSTR Directory)
{
    HANDLE hFind;
    WIN32_FIND_DATA FindData;

    char SearchName[1024],FullPath[1024];

    memset(SearchName,0,sizeof(SearchName));
    memset(&FindData,0,sizeof(WIN32_FIND_DATA));

    sprintf(SearchName,"%s\\*",Directory);

    hFind=FindFirstFile(SearchName,&FindData);

    if(hFind!=INVALID_HANDLE_VALUE)
    {
        while(FindNextFile(hFind,&FindData))
        {
            if(FindData.cFileName[0]=='.')
            {
                continue;
            }
           
            memset(FullPath,0,sizeof(FullPath));
            sprintf(FullPath,"%s\\%s",Directory,FindData.cFileName);

            if(FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
              MessageBoxA(NULL, FullPath, "Directory", MB_OK);
                SearchFile(FullPath);
            }

            else
            {
                MessageBoxA(NULL, FullPath, "File", MB_OK);
            }

        }

        FindClose(hFind);
    }
}

It also needs to be kept pure C and use the win32 api.


RE: Iterate over directories (non-recursive) - SIM-3437924 - Aug 15, 2020

EDIT:
I'll ask a different question. Why does the code below not work the same as the code in my first post above.
Code
char* Directory = "D:\\test_location";

label:
HANDLE hFind;
WIN32_FIND_DATA FindData;

char SearchName[1024], FullPath[1024];


memset(SearchName, 0, sizeof(SearchName));
memset(&FindData, 0, sizeof(WIN32_FIND_DATA));

sprintf(SearchName, "%s\\*", Directory);

hFind = FindFirstFile(SearchName, &FindData);

if (hFind != INVALID_HANDLE_VALUE)
{
while (FindNextFile(hFind, &FindData))
{
if (FindData.cFileName[0] == '.')
{
continue;
}

memset(FullPath, 0, sizeof(FullPath));                           


sprintf(FullPath, "%s\\%s", Directory, FindData.cFileName);
//MessageBoxA(NULL, FullPath, "FullPath", MB_OK);

if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
MessageBoxA(NULL, Directory, "Directory", MB_OK);
char cArray[1024];
memset(cArray, 0, sizeof(cArray));
sprintf(cArray, "%s", FullPath);
Directory = cArray;
goto label;
//SearchFile(FullPath);
}

else
{
MessageBoxA(NULL, FullPath, "File", MB_OK);
}
}

FindClose(hFind);
}