-
Notifications
You must be signed in to change notification settings - Fork 68
/
readdir.c
98 lines (85 loc) · 1.59 KB
/
readdir.c
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#define WIN32_LEAN_AND_MEAN
#include <errno.h>
#include <stdlib.h>
#include <windows.h> // FindFirstFile, FindNextFile
#include "readdir.h"
typedef struct dir_private
{
HANDLE h;
int first_read;
struct dirent buf;
} DIR;
DIR *opendir(const char *name)
{
DIR *ret = NULL;
char name2[MAX_PATH];
WIN32_FIND_DATAA findData;
if (strlen(name) >= MAX_PATH - 2 - 1)
{
errno = ENAMETOOLONG;
return ret;
}
strcpy(name2, name);
strcat(name2, "/*");
if (!(ret = (DIR *)malloc(sizeof(DIR))))
{
errno = ENOMEM;
return ret;
}
ret->h = FindFirstFileA(name2, &findData);
if (ret->h == INVALID_HANDLE_VALUE)
{
DWORD err = GetLastError();
free(ret);
ret = NULL;
switch (err)
{
case ERROR_FILE_NOT_FOUND: errno = ENOENT; break;
case ERROR_PATH_NOT_FOUND: errno = ENOENT; break;
case ERROR_ACCESS_DENIED: errno = EACCES; break;
case ERROR_DIRECTORY: errno = ENOTDIR; break;
default: errno = EINVAL;
}
return ret;
}
strcpy(ret->buf.d_name, findData.cFileName);
ret->first_read = 1;
return ret;
}
struct dirent *readdir(DIR *dir)
{
WIN32_FIND_DATAA findData;
if (!dir)
{
errno = EBADF;
return NULL;
}
if (dir->first_read)
{
dir->first_read = 0;
return &dir->buf;
}
if (!FindNextFileA(dir->h, &findData))
{
switch (GetLastError())
{
case ERROR_NO_MORE_FILES: errno = ENOENT; break;
case ERROR_INVALID_HANDLE: errno = EBADF; break;
default: errno = EINVAL;
}
return NULL;
}
strcpy(dir->buf.d_name, findData.cFileName);
return &dir->buf;
}
int closedir(DIR *dir)
{
if (!dir)
{
errno = EBADF;
return -1;
}
FindClose(dir->h);
free(dir);
return 0;
}