ls.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #include <LibC/stdio.h>
  2. #include <LibC/unistd.h>
  3. #include <LibC/dirent.h>
  4. #include <LibC/errno.h>
  5. #include <LibC/string.h>
  6. static int do_dir(const char* path);
  7. int main(int argc, char** argv)
  8. {
  9. if (argc == 2) {
  10. return do_dir(argv[1]);
  11. }
  12. return do_dir(".");
  13. }
  14. int do_dir(const char* path)
  15. {
  16. DIR* dirp = opendir(path);
  17. if (!dirp) {
  18. perror("opendir");
  19. return 1;
  20. }
  21. bool colorize = true;
  22. char pathbuf[256];
  23. while (auto* de = readdir(dirp)) {
  24. sprintf(pathbuf, "%s/%s", path, de->d_name);
  25. struct stat st;
  26. int rc = lstat(pathbuf, &st);
  27. if (rc == -1) {
  28. printf("lstat(%s) failed: %s\n", pathbuf, strerror(errno));
  29. return 2;
  30. }
  31. printf("%08u ", de->d_ino);
  32. if (S_ISDIR(st.st_mode))
  33. printf("d");
  34. else if (S_ISLNK(st.st_mode))
  35. printf("l");
  36. else if (S_ISBLK(st.st_mode))
  37. printf("b");
  38. else if (S_ISCHR(st.st_mode))
  39. printf("c");
  40. else if (S_ISFIFO(st.st_mode))
  41. printf("f");
  42. else if (S_ISREG(st.st_mode))
  43. printf("-");
  44. else
  45. printf("?");
  46. printf("%c%c%c%c%c%c%c%c",
  47. st.st_mode & S_IRUSR ? 'r' : '-',
  48. st.st_mode & S_IWUSR ? 'w' : '-',
  49. st.st_mode & S_IXUSR ? 'x' : '-',
  50. st.st_mode & S_IRGRP ? 'r' : '-',
  51. st.st_mode & S_IWGRP ? 'w' : '-',
  52. st.st_mode & S_IXGRP ? 'x' : '-',
  53. st.st_mode & S_IROTH ? 'r' : '-',
  54. st.st_mode & S_IWOTH ? 'w' : '-'
  55. );
  56. if (st.st_mode & S_ISVTX)
  57. printf("t");
  58. else
  59. printf("%c", st.st_mode & S_IXOTH ? 'x' : '-');
  60. printf(" %4u %4u", st.st_uid, st.st_gid);
  61. printf(" %10u ", st.st_size);
  62. const char* beginColor = "";
  63. const char* endColor = "";
  64. if (colorize) {
  65. if (S_ISLNK(st.st_mode))
  66. beginColor = "\033[36;1m";
  67. else if (S_ISDIR(st.st_mode))
  68. beginColor = "\033[34;1m";
  69. else if (st.st_mode & 0111)
  70. beginColor = "\033[32;1m";
  71. else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))
  72. beginColor = "\033[33;1m";
  73. endColor = "\033[0m";
  74. }
  75. printf("%s%s%s", beginColor, de->d_name, endColor);
  76. if (S_ISLNK(st.st_mode)) {
  77. char linkbuf[256];
  78. ssize_t nread = readlink(pathbuf, linkbuf, sizeof(linkbuf));
  79. if (nread < 0) {
  80. perror("readlink failed");
  81. } else {
  82. printf(" -> %s", linkbuf);
  83. }
  84. } else if (S_ISDIR(st.st_mode)) {
  85. printf("/");
  86. } else if (st.st_mode & 0111) {
  87. printf("*");
  88. }
  89. printf("\n");
  90. }
  91. return 0;
  92. }