cat.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. io_putstr("cat: unknown device or invalid path\n");
  22. return;
  23. }
  24. n = fat_resolve_path(fs, fs_path, &dir_cluster, name_8_3);
  25. if (n == -2) {
  26. io_putstr("cat: disk error\n");
  27. return;
  28. }
  29. if (n != 0) {
  30. io_putstr("cat: not found\n");
  31. return;
  32. }
  33. n = fat_read_file_in(fs, dir_cluster, name_8_3, buf, DUMP_BUF_SIZE);
  34. if (n == -2) {
  35. io_putstr("cat: disk read error\n");
  36. return;
  37. }
  38. if (n < 0) {
  39. io_putstr("cat: file not found\n");
  40. return;
  41. }
  42. for (i = 0; i < (unsigned int)n; i++) {
  43. unsigned char c = buf[i];
  44. if (c >= 0x20 && c < 0x7F)
  45. io_putchar((char)c);
  46. else if (c == '\n')
  47. io_putchar('\n');
  48. else if (c == '\t')
  49. io_putchar('\t');
  50. else
  51. io_putchar('.');
  52. }
  53. if (n > 0 && buf[n - 1] != '\n')
  54. io_putstr("\n");
  55. }