blob: c2d1b9c895624ca30db7a47638d890a2281a82f3 (
plain)
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
|
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
DIR *opendir(const char *name) {
FILE *fp = NULL;
DIR *dir = NULL;
fp = fopen(name, "r");
if (!fp) {
goto err;
}
dir = calloc(1, sizeof *dir);
if (!dir) {
goto err;
}
dir->fp = fp;
return dir;
err:
if (fp) fclose(fp);
free(dir);
return NULL;
}
int closedir(DIR *dir) {
fclose(dir->fp);
free(dir);
return 0;
}
struct dirent *readdir(DIR *dir) {
int i = 0;
char *buf = dir->dent.d_name;
for (;;) {
int c = fgetc(dir->fp);
if (c == EOF) {
if (i == 0) return NULL;
else break;
}
if (c == '\0') {
break;
}
if (i == sizeof(dir->dent.d_name)-1) {
/* overflow */
for (;;) {
c = fgetc(dir->fp);
if (c == EOF || c == '\0') break;
}
return errno = ENAMETOOLONG, NULL;
}
buf[i++] = c;
}
buf[i] = '\0';
return &dir->dent;
}
|