This source file includes following definitions.
- fmtname
- ls
- main
1 #include "kernel/types.h"
2 #include "kernel/stat.h"
3 #include "user/user.h"
4 #include "kernel/fs.h"
5 #include "kernel/fcntl.h"
6
7 char *
8 fmtname(char *path)
9 {
10 static char buf[DIRSIZ + 1];
11 char *p;
12
13
14 for (p = path + strlen(path); p >= path && *p != '/'; p--)
15 ;
16 p++;
17
18
19 if (strlen(p) >= DIRSIZ)
20 return p;
21 memmove(buf, p, strlen(p));
22 memset(buf + strlen(p), ' ', DIRSIZ - strlen(p));
23 buf[sizeof(buf) - 1] = '\0';
24 return buf;
25 }
26
27 void
28 ls(char *path)
29 {
30 char buf[512], *p;
31 int fd;
32 struct dirent de;
33 struct stat st;
34
35 if ((fd = open(path, O_RDONLY)) < 0) {
36 fprintf(2, "ls: cannot open %s\n", path);
37 return;
38 }
39
40 if (fstat(fd, &st) < 0) {
41 fprintf(2, "ls: cannot stat %s\n", path);
42 close(fd);
43 return;
44 }
45
46 switch (st.type) {
47 case T_DEVICE:
48 case T_FILE:
49 printf("%s %d %d %d\n", fmtname(path), st.type, st.ino, (int)st.size);
50 break;
51
52 case T_DIR:
53 if (strlen(path) + 1 + DIRSIZ + 1 > sizeof buf) {
54 printf("ls: path too long\n");
55 break;
56 }
57 strcpy(buf, path);
58 p = buf + strlen(buf);
59 *p++ = '/';
60 while (read(fd, &de, sizeof(de)) == sizeof(de)) {
61 if (de.inum == 0)
62 continue;
63 memmove(p, de.name, DIRSIZ);
64 p[DIRSIZ] = 0;
65 if (stat(buf, &st) < 0) {
66 printf("ls: cannot stat %s\n", buf);
67 continue;
68 }
69 printf("%s %d %d %d\n", fmtname(buf), st.type, st.ino, (int)st.size);
70 }
71 break;
72 }
73 close(fd);
74 }
75
76 int
77 main(int argc, char *argv[])
78 {
79 int i;
80
81 if (argc < 2) {
82 ls(".");
83 exit(0);
84 }
85 for (i = 1; i < argc; i++)
86 ls(argv[i]);
87 exit(0);
88 }