qsort.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include <stdio.h>
  2. #include <dirent.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. static 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. /* Even though some manpages say that alphasort should be
  34. * int alphasort(const void *a, const void *b),
  35. * in reality glibc and uclibc have const struct dirent**
  36. * instead of const void*.
  37. * Therefore we get a warning here unless we use a cast,
  38. * which makes people think that alphasort prototype
  39. * needs to be fixed in uclibc headers.
  40. */
  41. qsort(array, numdir, sizeof(struct dirent *), (void*) alphasort);
  42. for (i = 0; i < numdir; ++i) {
  43. dirbuf = array[i];
  44. printf("[%d] %s\n", i, dirbuf->d_name);
  45. free(array[i]);
  46. }
  47. free(array);
  48. return (0);
  49. }