-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlistdir.c
68 lines (56 loc) · 1.44 KB
/
listdir.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
#include <stdbool.h>
#include <sys/types.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
static int runforpath(const char *path);
static size_t listdiratpath(const char *path);
int main(int argc, char **argv) {
int status = EXIT_SUCCESS;
for (int argi = 1; argi < argc; ++argi) {
status = runforpath(argv[argi]);
}
return status;
}
static int runforpath(const char *path) {
return listdiratpath(path) != (size_t)-1
? EXIT_SUCCESS
: EXIT_FAILURE;
}
static void printpath(unsigned depth, const char *name) {
for (unsigned d = 0; d < depth; ++d) fputc('\t', stdout);
printf("%s\n", name);
}
static size_t listdiratpath(const char *path) {
size_t count = 0;
DIR *stream = opendir(path);
if (!stream) {
perror("Couldn't open directory");
return -1;
}
int olddirfd = open(".", O_RDONLY);
chdir(path);
static unsigned depth = 0;
struct dirent entry;
struct dirent *result = NULL;
while ((readdir_r(stream, &entry, &result) == 0) && result) {
if (strcmp(entry.d_name, ".") == 0) continue;
if (strcmp(entry.d_name, "..") == 0) continue;
printpath(depth, entry.d_name);
if (entry.d_type == DT_DIR) {
++depth;
count += listdiratpath(entry.d_name);
--depth;
}
}
int fchdir_result = fchdir(olddirfd);
if (fchdir_result != 0)
perror("Could not restore current directory");
closedir(stream);
return count;
}