ls.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* ls command: list a directory. `ls` / `ls /` lists mounted filesystems;
  2. * `ls /<device>[/dir]` lists a directory on that filesystem. */
  3. #include "fat.h"
  4. #include "io.h"
  5. #include "vfs.h"
  6. #define BUF_SIZE 12
  7. static void list_cb(const char *name, int is_dir, unsigned int size)
  8. {
  9. unsigned int i;
  10. char buf[BUF_SIZE];
  11. unsigned int n;
  12. for (i = 0; i < 11 && name[i]; i++)
  13. io_putchar(name[i] == ' ' ? ' ' : name[i]);
  14. if (i < 11)
  15. io_putchar(' ');
  16. if (is_dir) {
  17. io_putstr(" <DIR>\n");
  18. return;
  19. }
  20. io_putstr(" ");
  21. n = size;
  22. if (n == 0) {
  23. io_putchar('0');
  24. } else {
  25. buf[0] = '\0';
  26. i = BUF_SIZE - 1;
  27. buf[i] = '\0';
  28. while (n && i > 0) {
  29. buf[--i] = (char)('0' + (n % 10));
  30. n /= 10;
  31. }
  32. io_putstr(buf + i);
  33. }
  34. io_putstr("\n");
  35. }
  36. void program_ls_main(const char *path)
  37. {
  38. fat_fs_t *fs;
  39. const char *fs_path;
  40. unsigned int dir_cluster;
  41. int r;
  42. vfs_mount_all();
  43. if (!path || !path[0] || (path[0] == '/' && path[1] == '\0')) {
  44. vfs_list_root();
  45. return;
  46. }
  47. if (vfs_resolve(path, &fs, &fs_path) != 0) {
  48. if (vfs_device_known(path))
  49. io_putstr("ls: no filesystem on device\n");
  50. else
  51. io_putstr("ls: no such device\n");
  52. return;
  53. }
  54. r = fat_resolve_dir(fs, fs_path, &dir_cluster);
  55. if (r == -2) {
  56. io_putstr("ls: disk error\n");
  57. return;
  58. }
  59. if (r != 0) {
  60. io_putstr("ls: not a directory\n");
  61. return;
  62. }
  63. r = fat_list_dir(fs, dir_cluster, list_cb);
  64. if (r == -2)
  65. io_putstr("ls: disk read error\n");
  66. }