blob: 61d8a484fe3eaa44fa2e80d360cbb14dee80b904 (
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
|
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
DIR *opendir(const char *name) {
return opendir_f(fopen(name, "r"));
}
DIR *opendir_f(FILE *fp) {
if (!fp) return NULL;
DIR *dir;
dir = calloc(1, sizeof *dir);
if (!dir) {
fclose(fp);
return NULL;
}
dir->fp = fp;
return dir;
}
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;
}
|