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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
|
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int
recursive_list_dirs(const char *directory)
{
DIR *dir = opendir(directory);
if(dir == NULL) {
fprintf(stderr, "ls: %s: %s\n", directory, strerror(errno));
return 1;
}
struct dirent *ent;
while((ent = readdir(dir)) != NULL) {
if(ent->d_type == DT_DIR) {
char path[1024];
if(!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
snprintf(path, sizeof(path), "%s/%s", directory, ent->d_name);
printf("%s/%s\n", path, ent->d_name);
recursive_list_dirs(path);
} else
printf("%s\n", ent->d_name);
}
closedir(dir);
return 0;
}
int
main(int argc, char *argv[])
{
int c;
int all, show_slash, show_line, show_suffix, recursive;
all = show_slash = show_line = show_suffix = recursive = 0;
while((c = getopt(argc, argv, "1FRahlp")) != -1) {
switch(c) {
case '1':
show_line = 1;
break;
case 'F':
show_suffix = 1;
show_slash = 1;
break;
case 'R':
recursive = 1;
break;
case 'a':
all = 1;
break;
case 'h':
printf("usage: ls [-1FRalp] [file...]\n");
return 0;
case 'l':
show_line = 1;
break;
case 'p':
show_slash = 1;
break;
}
}
for(; optind < argc; optind++) {
char directory[256];
if(!argv[optind])
strcpy(directory, "./");
else
strcpy(directory, argv[optind]); /* Very dirty code, i'll fix it
* later */
DIR *dir = opendir(directory);
if(dir == NULL) {
/* maybe we were given a file? */
fprintf(stderr, "ls: %s: %s\n", directory, strerror(errno));
continue;
}
struct dirent *ent;
if(recursive) {
recursive_list_dirs(directory);
return 0;
}
char suffix, separator;
suffix = separator = 0;
if(!show_line && isatty(STDOUT_FILENO))
separator = ' ';
else
separator = '\n';
if(dir != NULL) {
while((ent = readdir(dir)) != NULL) {
suffix = 0;
if(ent->d_name[0] == '.' && !all)
continue;
if(show_slash && ent->d_type == DT_DIR)
suffix = '/';
if(show_suffix) {
switch(ent->d_type) {
case DT_REG:
/* check if executable */
; /* statement after label */
struct stat st;
if(fstatat(dirfd(dir),
ent->d_name,
&st,
AT_SYMLINK_NOFOLLOW) < 0) {
fprintf(stderr,
"ls: %s: %s\n",
ent->d_name,
strerror(errno));
return 1;
}
if((st.st_mode & S_IEXEC) != 0)
suffix = '*';
break;
case DT_FIFO:
suffix = '|';
break;
case DT_LNK:
suffix = '@';
break;
case DT_SOCK:
suffix = '=';
break;
}
}
if(suffix != 0)
printf("%s%c%c", ent->d_name, suffix, separator);
else
printf("%s%c", ent->d_name, separator);
}
}
puts("");
closedir(dir);
}
return 0;
}
|