cat.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* cat command: print file contents to screen. Usage: cat /<device>/<file>. */
  2. #include "fat.h"
  3. #include "io.h"
  4. #include "vfs.h"
  5. #define DUMP_BUF_SIZE 4096
  6. void program_cat_main(const char *filename)
  7. {
  8. static unsigned char buf[DUMP_BUF_SIZE];
  9. fat_fs_t *fs;
  10. const char *fs_path;
  11. unsigned int dir_cluster;
  12. char name_8_3[12];
  13. int n;
  14. unsigned int i;
  15. if (!filename || !filename[0]) {
  16. io_putstr("cat: usage cat /<device>/<file>\n");
  17. return;
  18. }
  19. vfs_mount_all();
  20. if (vfs_resolve(filename, &fs, &fs_path) != 0) {
  21. if (vfs_device_known(filename))
  22. io_putstr("cat: no filesystem on device\n");
  23. else
  24. io_putstr("cat: no such device\n");
  25. return;
  26. }
  27. n = fat_resolve_path(fs, fs_path, &dir_cluster, name_8_3);
  28. if (n == -2) {
  29. io_putstr("cat: disk error\n");
  30. return;
  31. }
  32. if (n != 0) {
  33. io_putstr("cat: not found\n");
  34. return;
  35. }
  36. n = fat_read_file_in(fs, dir_cluster, name_8_3, buf, DUMP_BUF_SIZE);
  37. if (n == -2) {
  38. io_putstr("cat: disk read error\n");
  39. return;
  40. }
  41. if (n < 0) {
  42. io_putstr("cat: file not found\n");
  43. return;
  44. }
  45. for (i = 0; i < (unsigned int)n; i++) {
  46. unsigned char c = buf[i];
  47. if (c >= 0x20 && c < 0x7F)
  48. io_putchar((char)c);
  49. else if (c == '\n')
  50. io_putchar('\n');
  51. else if (c == '\t')
  52. io_putchar('\t');
  53. else
  54. io_putchar('.');
  55. }
  56. if (n > 0 && buf[n - 1] != '\n')
  57. io_putstr("\n");
  58. }