Skip to content
Snippets Groups Projects
ls.c 1.5 KiB
Newer Older
kaashoek's avatar
kaashoek committed
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fs.h"

rsc's avatar
 
rsc committed
char*
fmtname(char *path)
kaashoek's avatar
kaashoek committed
{
rsc's avatar
 
rsc committed
  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;
kaashoek's avatar
kaashoek committed
}

rsc's avatar
 
rsc committed
void
ls(char *path)
kaashoek's avatar
kaashoek committed
{
rsc's avatar
rsc committed
  char buf[512], *p;
kaashoek's avatar
kaashoek committed
  int fd;
rsc's avatar
rsc committed
  struct dirent de;
  struct stat st;
rsc's avatar
 
rsc committed
  
  if((fd = open(path, 0)) < 0){
    printf(2, "ls: cannot open %s\n", path);
    return;
kaashoek's avatar
kaashoek committed
  }
rsc's avatar
 
rsc committed
  
  if(fstat(fd, &st) < 0){
    printf(2, "ls: cannot stat %s\n", path);
    close(fd);
    return;
kaashoek's avatar
kaashoek committed
  }
rsc's avatar
 
rsc committed
  
  switch(st.type){
kaashoek's avatar
kaashoek committed
  case T_FILE:
rsc's avatar
 
rsc committed
    printf(1, "%s %d %d %d\n", fmtname(path), st.type, st.ino, st.size);
kaashoek's avatar
kaashoek committed
    break;
rsc's avatar
 
rsc committed
  
kaashoek's avatar
kaashoek committed
  case T_DIR:
rsc's avatar
 
rsc committed
    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;
rsc's avatar
 
rsc committed
      printf(1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size);
kaashoek's avatar
kaashoek committed
    }
kaashoek's avatar
kaashoek committed
    break;
kaashoek's avatar
kaashoek committed
  }
  close(fd);
rsc's avatar
 
rsc committed
}

int
main(int argc, char *argv[])
{
  int i;

  if(argc < 2){
    ls(".");
    exit();
  }
  for(i=1; i<argc; i++)
    ls(argv[i]);
kaashoek's avatar
kaashoek committed
  exit();
}