qsort.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <stdio.h>
  2. #include <dirent.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. int select_files(const struct dirent *dirbuf)
  6. {
  7. if (dirbuf->d_name[0] == '.')
  8. return 0;
  9. else
  10. return 1;
  11. }
  12. int main(void)
  13. {
  14. struct dirent **array;
  15. struct dirent *dirbuf;
  16. int i, numdir;
  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");
  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. }