user/ls.c

88 lines
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"67char*8fmtname(char *path)9{10  static char buf[DIRSIZ+1];11  char *p;1213  // Find first character after last slash.14  for(p=path+strlen(path); p >= path && *p != '/'; p--)15    ;16  p++;1718  // Return blank-padded name.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}2627void28ls(char *path)29{30  char buf[512], *p;31  int fd;32  struct dirent de;33  struct stat st;3435  if((fd = open(path, O_RDONLY)) < 0){36    fprintf(2, "ls: cannot open %s\n", path);37    return;38  }3940  if(fstat(fd, &st) < 0){41    fprintf(2, "ls: cannot stat %s\n", path);42    close(fd);43    return;44  }4546  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;5152  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}7576int77main(int argc, char *argv[])78{79  int i;8081  if(argc < 2){82    ls(".");83    exit(0);84  }85  for(i=1; i<argc; i++)86    ls(argv[i]);87  exit(0);88}89