cat.c 915 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <stdlib.h>
  6. #include <sys/fcntl.h>
  7. #include <sys/types.h>
  8. #include "cfs.h"
  9. int main(int argc, const char **argv) {
  10. char *fname = (char *) argv[1];
  11. char *file = (char *) argv[2];
  12. int fd;
  13. if (!fname) {
  14. printf("usage: cat device file-name. \n");
  15. return 1;
  16. }
  17. fd = open(fname, O_RDWR);
  18. if (fd < 0) {
  19. printf("failed when trying to open %s: %s\n", fname, strerror(errno));
  20. return 1;
  21. }
  22. cfs_init(fd);
  23. struct inode *ino = cfs_search(rootdir, file);
  24. if (!ino) {
  25. printf("fatal: %s not found. \n", file);
  26. close(fd);
  27. return 1;
  28. }
  29. char *buf = malloc(fsize(ino));
  30. if (!buf) {
  31. printf("failed when allocate space: %d bytes need. \n", fsize(ino));
  32. close(fd);
  33. return 1;
  34. }
  35. cfs_read(ino, buf, fsize(ino));
  36. int i;
  37. for (i = 0; i < fsize(ino); i++)
  38. putc(buf[i], stdout);
  39. close(fd);
  40. return 0;
  41. }