ls.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. io_putstr("ls: unknown device or invalid path\n");
  49. return;
  50. }
  51. r = fat_resolve_dir(fs, fs_path, &dir_cluster);
  52. if (r == -2) {
  53. io_putstr("ls: disk error\n");
  54. return;
  55. }
  56. if (r != 0) {
  57. io_putstr("ls: not a directory\n");
  58. return;
  59. }
  60. r = fat_list_dir(fs, dir_cluster, list_cb);
  61. if (r == -2)
  62. io_putstr("ls: disk read error\n");
  63. }