| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
#ifndef DIRENT_WIN32_H |
| 6 |
#define DIRENT_WIN32_H |
| 7 |
|
| 8 |
#ifdef _MSC_VER |
| 9 |
|
| 10 |
#include <windows.h> |
| 11 |
#include <errno.h> |
| 12 |
#include <string.h> |
| 13 |
|
| 14 |
struct dirent { |
| 15 |
char d_name[MAX_PATH]; |
| 16 |
}; |
| 17 |
|
| 18 |
typedef struct { |
| 19 |
HANDLE hFind; |
| 20 |
WIN32_FIND_DATAA fdata; |
| 21 |
struct dirent entry; |
| 22 |
bool first; |
| 23 |
} DIR; |
| 24 |
|
| 25 |
static inline DIR *opendir(const char *name) |
| 26 |
{ |
| 27 |
char path[MAX_PATH]; |
| 28 |
size_t len = strlen(name); |
| 29 |
|
| 30 |
if (len == 0 || len + 3 > MAX_PATH) { |
| 31 |
errno = ENOENT; |
| 32 |
return NULL; |
| 33 |
} |
| 34 |
|
| 35 |
snprintf(path, MAX_PATH, "%s\\*", name); |
| 36 |
|
| 37 |
DIR *dir = (DIR *)malloc(sizeof(DIR)); |
| 38 |
if (!dir) { |
| 39 |
errno = ENOMEM; |
| 40 |
return NULL; |
| 41 |
} |
| 42 |
|
| 43 |
dir->hFind = FindFirstFileA(path, &dir->fdata); |
| 44 |
if (dir->hFind == INVALID_HANDLE_VALUE) { |
| 45 |
free(dir); |
| 46 |
errno = ENOENT; |
| 47 |
return NULL; |
| 48 |
} |
| 49 |
|
| 50 |
dir->first = true; |
| 51 |
return dir; |
| 52 |
} |
| 53 |
|
| 54 |
static inline struct dirent *readdir(DIR *dir) |
| 55 |
{ |
| 56 |
if (!dir) |
| 57 |
return NULL; |
| 58 |
|
| 59 |
if (dir->first) { |
| 60 |
dir->first = false; |
| 61 |
} else { |
| 62 |
if (!FindNextFileA(dir->hFind, &dir->fdata)) |
| 63 |
return NULL; |
| 64 |
} |
| 65 |
|
| 66 |
strncpy(dir->entry.d_name, dir->fdata.cFileName, MAX_PATH); |
| 67 |
dir->entry.d_name[MAX_PATH - 1] = '\0'; |
| 68 |
return &dir->entry; |
| 69 |
} |
| 70 |
|
| 71 |
static inline int closedir(DIR *dir) |
| 72 |
{ |
| 73 |
if (!dir) |
| 74 |
return -1; |
| 75 |
|
| 76 |
FindClose(dir->hFind); |
| 77 |
free(dir); |
| 78 |
return 0; |
| 79 |
} |
| 80 |
|
| 81 |
#else |
| 82 |
|
| 83 |
#include <dirent.h> |
| 84 |
|
| 85 |
#endif |
| 86 |
|
| 87 |
#endif |