ls.c 1.0 KB

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