cat.c 1.3 KB

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