dirent.c 705 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <dirent.h>
  7. #define _DTIFY(DT) [DT] #DT
  8. const char * const types[] = {
  9. _DTIFY(DT_UNKNOWN),
  10. _DTIFY(DT_FIFO),
  11. _DTIFY(DT_CHR),
  12. _DTIFY(DT_DIR),
  13. _DTIFY(DT_BLK),
  14. _DTIFY(DT_REG),
  15. _DTIFY(DT_LNK),
  16. _DTIFY(DT_SOCK),
  17. _DTIFY(DT_WHT)
  18. };
  19. int main(int argc, char *argv[])
  20. {
  21. DIR *dirh;
  22. struct dirent *de;
  23. const char *mydir = (argc == 1 ? "/" : argv[1]);
  24. if ((dirh = opendir(mydir)) == NULL) {
  25. perror("opendir");
  26. return 1;
  27. }
  28. printf("readdir() says:\n");
  29. while ((de = readdir(dirh)) != NULL)
  30. printf("\tdir entry %s: %s\n", types[de->d_type], de->d_name);
  31. closedir(dirh);
  32. return 0;
  33. }