Logo  

CS471/571 - Operating Systems

Displaying ./code/Xv6/fsls/ls.c

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#define min(a, b)       ((a) < (b)? (a) : (b))

typedef unsigned short ushort;
typedef unsigned int uint;

#include "fs.h"

char *filetype[] = {"?", "dir", "regular", "device" };
typedef enum { UNKNOWN = 0, DIR =1, REGULAR = 2, DEVICE = 3 } ftype;

int fsfd;
struct superblock sb;

int readinode(int inum, struct dinode *di)
{
  lseek(fsfd, (sb.inodestart*BSIZE) + inum*sizeof(struct dinode), SEEK_SET);
  return read(fsfd, di, sizeof(struct dinode));
}

int readblock(int blkno, unsigned char *buf)
{
  lseek(fsfd, blkno*BSIZE, SEEK_SET);
  return read(fsfd, buf, BSIZE);
}

int main(int argc, char *argv[])
{
  if (argc < 2) {
    printf("Usage: ls <fs.img> [<inode #>]\n");
    return 1;
  }

  fsfd = open(argv[1], O_RDONLY);
  if (fsfd < 0) {
    perror("fs open");
    return 1;
  }
  int inode = 1;
  if (argc > 2) inode = atoi(argv[2]);

  lseek(fsfd, BSIZE, SEEK_SET);
  read(fsfd, &sb, sizeof(struct superblock));

  struct dinode di;

  readinode(inode, &di);
  char data[BSIZE];
  struct dirent *de;

  readblock(di.addrs[0], data);
  de = (struct dirent *)data;

  int size = di.size;

  while (size > 0) {
    if (de->inum)
      printf("[%4d] \"%.14s\"\n", de->inum, de->name);

    de++;
    size -= sizeof(struct dirent);
  }

  return 0;
}