Skip to content

Instantly share code, notes, and snippets.

@masterzorag
Last active September 30, 2015 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masterzorag/717fb02d6f3b6938a0fd to your computer and use it in GitHub Desktop.
Save masterzorag/717fb02d6f3b6938a0fd to your computer and use it in GitHub Desktop.
C scanning directory: qsort
/*
http://www.scs.stanford.edu/histar/src/pkg/uclibc/test/stdlib/qsort.c
gcc -o qsort qsort.c -Wall
*/
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h> // /usr/include/stdlib.h:764:13: note: expected ‘__compar_fn_t’ but argument is of type ‘int (*)(const struct dirent **, const struct dirent **)’
#include <unistd.h>
static int select_files(const struct dirent *dirbuf)
{
if (dirbuf->d_name[0] == '.')
return 0;
else
return 1;
}
int main(void)
{
struct dirent **array;
struct dirent *dirbuf;
int i, numdir;
/* The scandir() function reads the directory dirname and builds an array
of pointers to directory entries, using malloc() to allocate the space.
You can deallocate the memory allocated for the array by calling free().
Free each pointer in the array, and then free the array itself. */
chdir("/");
// 1: scandir only
numdir = scandir(".", &array, select_files, NULL);
printf("\nGot %d entries from scandir().\n", numdir);
for (i = 0; i < numdir; ++i) {
dirbuf = array[i];
printf("[%.2d] %s\n", i, dirbuf->d_name);
free(array[i]);
}
free(array);
// 2a: scandir + alphasort
numdir = scandir(".", &array, select_files, alphasort);
printf("\nGot %d entries from scandir() using alphasort().\n", numdir);
for (i = 0; i < numdir; ++i) {
dirbuf = array[i];
printf("[%.2d] %s\n", i, dirbuf->d_name);
}
// 2b, array is not freed yet: qsort (+ alphasort)
printf("\nCalling qsort()\n");
qsort(array, numdir, sizeof(struct dirent *), alphasort); // int (*)(const struct dirent **, const struct dirent **)
for (i = 0; i < numdir; ++i) {
dirbuf = array[i];
printf("[%.2d] %s\n", i, dirbuf->d_name);
free(array[i]);
}
free(array);
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment