Keven Diuliy
Keven Diuliy

Reputation: 131

List Files in C

I have a simple program that list files written in C. I'm just wondering what can I add to this code so the files print out in sorted order? Thanks

while ((directory = readdir(dir)) != NULL)
{
   printf("%s\n", directory->dir_name);
}

Upvotes: 1

Views: 741

Answers (3)

Déjà vu
Déjà vu

Reputation: 28830

You have first to store the names in an array, MAXDIRS is the max number of dirs (or you could use calloc to allocate dynamically the array)

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

char dirs[MAXDIRS][512]; // you have to ensure correct allocation (eg names < 512 chars)
int ndirs = 0; // number of dirs

while ((directory = readdir(dir)) != NULL) {
   strcpy(dirs[ ndirs++ ], directory->d_name);
}

// Then sort the directories

// need a sorting function
int comp(void const *a, void const *b) { 
    char const *u = (char const *)a;
    char const *v = (char const *)b;

    return strcmp(u, v);
}

// use qsort to sort the dirs
qsort (dirs, ndirs, sizeof(dirs[0]), comp);

dirs now contains a sorted array of directories

// display

int i;

for (i=0 ; i<ndirs ; i++) {
  printf("%s\n", dirs[i]);
}

Upvotes: 2

Travis Griggs
Travis Griggs

Reputation: 22252

I suggest you lookup qsort() and use that. You'll probably stumble on some other useful sorting APIs provided by your standard library as well.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206498

readdir() does not guarantee you any sorting order.
If you need the listing in any sorted order you will have to write the code for doing it. In short, collect all filenames in a array and then sort that array depending on your criteria of sorting.

You can use scandir() on linux platform.

Upvotes: 1

Related Questions