summaryrefslogtreecommitdiff
path: root/user/ls.c
diff options
context:
space:
mode:
authorRobert Morris <[email protected]>2019-06-11 09:57:14 -0400
committerRobert Morris <[email protected]>2019-06-11 09:57:14 -0400
commit5753553213df8f9de851adb68377db43faecb91f (patch)
tree3b629ff54897fca414146677532cb459a2ed11ba /user/ls.c
parent91ba81110acd3163f7de3580b677eece0c57f5e7 (diff)
downloadxv6-labs-5753553213df8f9de851adb68377db43faecb91f.tar.gz
xv6-labs-5753553213df8f9de851adb68377db43faecb91f.tar.bz2
xv6-labs-5753553213df8f9de851adb68377db43faecb91f.zip
separate source into kernel/ user/ mkfs/
Diffstat (limited to 'user/ls.c')
-rw-r--r--user/ls.c85
1 files changed, 85 insertions, 0 deletions
diff --git a/user/ls.c b/user/ls.c
new file mode 100644
index 0000000..c649c57
--- /dev/null
+++ b/user/ls.c
@@ -0,0 +1,85 @@
+#include "kernel/types.h"
+#include "kernel/stat.h"
+#include "user/user.h"
+#include "kernel/fs.h"
+
+char*
+fmtname(char *path)
+{
+ static char buf[DIRSIZ+1];
+ char *p;
+
+ // Find first character after last slash.
+ for(p=path+strlen(path); p >= path && *p != '/'; p--)
+ ;
+ p++;
+
+ // Return blank-padded name.
+ if(strlen(p) >= DIRSIZ)
+ return p;
+ memmove(buf, p, strlen(p));
+ memset(buf+strlen(p), ' ', DIRSIZ-strlen(p));
+ return buf;
+}
+
+void
+ls(char *path)
+{
+ char buf[512], *p;
+ int fd;
+ struct dirent de;
+ struct stat st;
+
+ if((fd = open(path, 0)) < 0){
+ printf(2, "ls: cannot open %s\n", path);
+ return;
+ }
+
+ if(fstat(fd, &st) < 0){
+ printf(2, "ls: cannot stat %s\n", path);
+ close(fd);
+ return;
+ }
+
+ switch(st.type){
+ case T_FILE:
+ printf(1, "%s %d %d %d\n", fmtname(path), st.type, st.ino, st.size);
+ break;
+
+ case T_DIR:
+ if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
+ printf(1, "ls: path too long\n");
+ break;
+ }
+ strcpy(buf, path);
+ p = buf+strlen(buf);
+ *p++ = '/';
+ while(read(fd, &de, sizeof(de)) == sizeof(de)){
+ if(de.inum == 0)
+ continue;
+ memmove(p, de.name, DIRSIZ);
+ p[DIRSIZ] = 0;
+ if(stat(buf, &st) < 0){
+ printf(1, "ls: cannot stat %s\n", buf);
+ continue;
+ }
+ printf(1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size);
+ }
+ break;
+ }
+ close(fd);
+}
+
+int
+main(int argc, char *argv[])
+{
+ int i;
+
+ if(argc < 2){
+ ls(".");
+ exit();
+ }
+ for(i=1; i<argc; i++)
+ ls(argv[i]);
+ exit();
+}