Directory Enumeration

Windows

Relevant documentation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <windows.h>

...

WIN32_FIND_DATA entry;
HANDLE find = FindFirstFile("SomeFolder\\*.*", &entry);
if (find != INVALID_HANDLE_VALUE)
{
    do {
        printf("Name: %s ", entry.cFileName);

        if (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
            printf("(Directory)\n");
        } else {
            printf("(File)\n");
        }
    } while (FindNextFile(find, &entry));

    FindClose(find);
}

UNIX

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>

...

DIR *directory = opendir("SomeFolder/")
struct dirent *entry;

if (directory) {
    while ((entry = readdir(directory)) {
        printf("Name: %s ", entry->d_name);

        char buffer[4096];
        sprintf("SomeFolder/%s", entry->d_name);
        struct stat s;
        stat(buffer, &s);

        if (S_ISDIR(s.st_mode)) {
            printf("(Directory)\n");
        } else {
            printf("(File)\n");
        }
    }

    closedir(directory);
}

Edited by Mārtiņš Možeiko on Reason: No point checking if find handle is invalid in every loop iteration