blob: a937457a9e1a56417a4e3bfcd0d6bb1ace74e5d4 (
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
/* TODO:
* - add flags
* - add option to print more file information
*/
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
void dirwalk(DIR *);
void error(char *);
void printdirent(struct dirent *);
void printfile(char *);
/* print information about files and directories */
int main(int argc, char **argv)
{
DIR *dp;
if (argc == 1) {
if ((dp = opendir(".")) == NULL) {
perror("ls");
return -1;
}
dirwalk(dp);
} else if (argc == 2) {
if ((dp = opendir(argv[1])) == NULL) {
perror("ls");
return -1;
}
dirwalk(dp);
} else {
while (--argc > 0 && !ferror(stdout)) {
errno = 0;
if ((dp = opendir(*++argv)) == NULL) {
perror("ls");
continue;
}
dirwalk(dp);
}
}
}
/* dirwalk: read all the directory entries in a directory */
void dirwalk(DIR *d)
{
struct dirent *dir;
while ((dir = readdir(d)) != NULL) {
errno = 0;
if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0)
continue;
printdirent(dir);
}
if (errno != 0) {
perror("ls");
}
}
/* printdirent: print a directory entry and any selected information */
void printdirent(struct dirent *dir)
{
printf("%s\n", dir->d_name);
}
/* printfile: print a file and any other selected information */
void printfile(char *name)
{
struct stat stbuf;
int e = stat(name, &stbuf);
if (e != 0) {
perror("ls");
return;
}
printf("%s\n", name);
}
|