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 return buf;
24 }
25
26 void
27 ls(char *path)
28 {
29 char buf[512], *p;
30 int fd;
31 struct dirent de;
32 struct stat st;
33
34 if((fd = open(path, O_RDONLY)) < 0){
35 fprintf(2, "ls: cannot open %s\n", path);
36 return;
37 }
38
39 if(fstat(fd, &st) < 0){
40 fprintf(2, "ls: cannot stat %s\n", path);
41 close(fd);
42 return;
43 }
44
45 switch(st.type){
46 case T_DEVICE:
47 case T_FILE:
48 printf("%s %d %d %d\n", fmtname(path), st.type, st.ino, (int) st.size);
49 break;
50
51 case T_DIR:
52 if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
53 printf("ls: path too long\n");
54 break;
55 }
56 strcpy(buf, path);
57 p = buf+strlen(buf);
58 *p++ = '/';
59 while(read(fd, &de, sizeof(de)) == sizeof(de)){
60 if(de.inum == 0)
61 continue;
62 memmove(p, de.name, DIRSIZ);
63 p[DIRSIZ] = 0;
64 if(stat(buf, &st) < 0){
65 printf("ls: cannot stat %s\n", buf);
66 continue;
67 }
68 printf("%s %d %d %d\n", fmtname(buf), st.type, st.ino, (int) st.size);
69 }
70 break;
71 }
72 close(fd);
73 }
74
75 int
76 main(int argc, char *argv[])
77 {
78 int i;
79
80 if(argc < 2){
81 ls(".");
82 exit(0);
83 }
84 for(i=1; i<argc; i++)
85 ls(argv[i]);
86 exit(0);
87 }