qsort.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <stdio.h>
  2. #include <dirent.h>
  3. #include <stdlib.h>
  4. int select_files(const struct dirent *dirbuf)
  5. {
  6. if (dirbuf->d_name[0] == '.')
  7. return 0;
  8. else
  9. return 1;
  10. }
  11. int main(void)
  12. {
  13. struct dirent **array;
  14. struct dirent *dirbuf;
  15. int i, numdir;
  16. chdir("/");
  17. numdir = scandir(".", &array, select_files, NULL);
  18. printf("\nGot %d entries from scandir().\n", numdir);
  19. for (i = 0; i < numdir; ++i) {
  20. dirbuf = array[i];
  21. printf("[%d] %s\n", i, dirbuf->d_name);
  22. free(array[i]);
  23. }
  24. free(array);
  25. numdir = scandir(".", &array, select_files, alphasort);
  26. printf("\nGot %d entries from scandir() using alphasort().\n", numdir);
  27. for (i = 0; i < numdir; ++i) {
  28. dirbuf = array[i];
  29. printf("[%d] %s\n", i, dirbuf->d_name);
  30. }
  31. printf("\nCalling qsort()\n", numdir);
  32. qsort(array, numdir, sizeof(struct dirent *), alphasort);
  33. for (i = 0; i < numdir; ++i) {
  34. dirbuf = array[i];
  35. printf("[%d] %s\n", i, dirbuf->d_name);
  36. free(array[i]);
  37. }
  38. free(array);
  39. return(0);
  40. }