cat.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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] != '.' && 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] != ' ' && 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. if (fat_init() != 0) {
  43. io_putstr("cat: fat init failed\n");
  44. return;
  45. }
  46. n = fat_read_file(name_8_3, buf, DUMP_BUF_SIZE);
  47. if (n == -2) {
  48. io_putstr("cat: disk read error\n");
  49. return;
  50. }
  51. if (n < 0) {
  52. io_putstr("cat: file not found\n");
  53. return;
  54. }
  55. for (i = 0; i < (unsigned int)n; i++) {
  56. unsigned char c = buf[i];
  57. if (c >= 0x20 && c < 0x7F)
  58. io_putchar((char)c);
  59. else if (c == '\n')
  60. io_putchar('\n');
  61. else if (c == '\t')
  62. io_putchar('\t');
  63. else
  64. io_putchar('.');
  65. }
  66. if (n > 0 && buf[n - 1] != '\n')
  67. io_putstr("\n");
  68. }