2016-07-27

C: Sorted Walk Through Directory Contents

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

void walk_dir(const char *path)
{
 struct dirent **namelist;
 int i, n;

 n = scandir(path, &namelist, NULL/*filter*/, alphasort);
 if (n < 0)
 {
  perror("scandir");
 } else {
  for (i = 0; i < n; i++) {
   printf("Entry: %s\n", namelist[i]->d_name);
   free(namelist[i]);
  }
  free(namelist);
 }
}

int main(void)
{
 walk_dir("/tmp");
 return EXIT_SUCCESS;
}

No comments :

Post a Comment