qsort.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. chdir("/");
  18. numdir = scandir(".", &array, select_files, NULL);
  19. printf("\nGot %d entries from scandir().\n", numdir);
  20. for (i = 0; i < numdir; ++i) {
  21. dirbuf = array[i];
  22. printf("[%d] %s\n", i, dirbuf->d_name);
  23. free(array[i]);
  24. }
  25. free(array);
  26. numdir = scandir(".", &array, select_files, alphasort);
  27. printf("\nGot %d entries from scandir() using alphasort().\n", numdir);
  28. for (i = 0; i < numdir; ++i) {
  29. dirbuf = array[i];
  30. printf("[%d] %s\n", i, dirbuf->d_name);
  31. }
  32. printf("\nCalling qsort()\n");
  33. qsort(array, numdir, sizeof(struct dirent *), alphasort);
  34. for (i = 0; i < numdir; ++i) {
  35. dirbuf = array[i];
  36. printf("[%d] %s\n", i, dirbuf->d_name);
  37. free(array[i]);
  38. }
  39. free(array);
  40. return(0);
  41. }