ls.c 976 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #define MINIRENT_IMPLEMENTATION
  7. #include <minirent.h>
  8. int main(int argc, char *argv[])
  9. {
  10. const char *dir_path = ".";
  11. if (argc >= 2) {
  12. dir_path = argv[1];
  13. }
  14. DIR *dir = opendir(dir_path);
  15. if (dir == NULL) {
  16. fprintf(stderr, "ERROR: could not open directory %s: %s\n",
  17. dir_path, strerror(errno));
  18. exit(1);
  19. }
  20. errno = 0;
  21. struct dirent *dp = NULL;
  22. while ((dp = readdir(dir))) {
  23. // TODO: the output of ls is not sorted
  24. printf("%s\n", dp->d_name);
  25. }
  26. if (errno) {
  27. fprintf(stderr, "ERROR: could not read directory %s: %s\n",
  28. dir_path, strerror(errno));
  29. exit(1);
  30. }
  31. if (closedir(dir) < 0) {
  32. fprintf(stderr, "ERROR: could not close directory %s: %s\n",
  33. dir_path, strerror(errno));
  34. exit(1);
  35. }
  36. return 0;
  37. }