cat.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* cat command: print file contents to screen. */
  2. #include "fat.h"
  3. #include "io.h"
  4. #define DUMP_BUF_SIZE 4096
  5. #define NAME_BUF_SIZE 12
  6. static void to_8_3(const char *in, unsigned int in_len, char *out)
  7. {
  8. unsigned int i, j, dot;
  9. for (i = 0; i < in_len && in[i] == ' '; i++)
  10. ;
  11. dot = i;
  12. while (dot < in_len && in[dot] != '\0' && in[dot] != '.' && in[dot] != ' ')
  13. dot++;
  14. j = 0;
  15. while (i < dot && j < 8) {
  16. out[j++] = (char)(in[i] >= 'a' && in[i] <= 'z' ? in[i] - 32 : in[i]);
  17. i++;
  18. }
  19. while (j < 8)
  20. out[j++] = ' ';
  21. if (i < in_len && in[i] == '.')
  22. i++;
  23. while (i < in_len && in[i] != '\0' && in[i] != ' ' && j < 11) {
  24. out[j++] = (char)(in[i] >= 'a' && in[i] <= 'z' ? in[i] - 32 : in[i]);
  25. i++;
  26. }
  27. while (j < 11)
  28. out[j++] = ' ';
  29. out[11] = '\0';
  30. }
  31. void program_cat_main(const char *filename)
  32. {
  33. static unsigned char buf[DUMP_BUF_SIZE];
  34. char name_8_3[NAME_BUF_SIZE];
  35. int n;
  36. unsigned int i;
  37. if (!filename || !filename[0]) {
  38. io_putstr("cat: usage cat <filename>\n");
  39. return;
  40. }
  41. to_8_3(filename, 64, name_8_3);
  42. n = fat_init();
  43. if (n == -2) {
  44. io_putstr("cat: disk read error\n");
  45. return;
  46. }
  47. if (n != 0) {
  48. io_putstr("cat: no FAT filesystem found\n");
  49. return;
  50. }
  51. n = fat_read_file(name_8_3, buf, DUMP_BUF_SIZE);
  52. if (n == -2) {
  53. io_putstr("cat: disk read error\n");
  54. return;
  55. }
  56. if (n < 0) {
  57. io_putstr("cat: file not found\n");
  58. return;
  59. }
  60. for (i = 0; i < (unsigned int)n; i++) {
  61. unsigned char c = buf[i];
  62. if (c >= 0x20 && c < 0x7F)
  63. io_putchar((char)c);
  64. else if (c == '\n')
  65. io_putchar('\n');
  66. else if (c == '\t')
  67. io_putchar('\t');
  68. else
  69. io_putchar('.');
  70. }
  71. if (n > 0 && buf[n - 1] != '\n')
  72. io_putstr("\n");
  73. }