Thursday, 22 August 2013

How to implement custom compar() for scandir()

How to implement custom compar() for scandir()

I've been reading the man pages of scandir(), alphasort() and have
evidently crammed them all. But still can't figure out how to implement a
custom comparision function.
Here's my code:
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
int mySort(char*, char*);
int (*fnPtr)(char*, char*);
int main(){
struct dirent **entryList;
fnPtr = &mySort;
int count = scandir(".",&entryList,NULL,fnptr);
for(count--;count>=0;count--){
printf("%s\n",entryList[count]->d_name);
}
return 0;
}
int mySort(const void* a, const void* b){
char *aNew, *bNew;
if(a[0] == '.'){
*aNew = removeDot(a);
}
else{
aNew = a;
}
if(b[0] == '.'){
*bNew = removeDot(b);
}
else{
bNew = b;
}
return alphasort(aNew, bNew);
}
Easy to see that am trying to alphabetically sort file names irrespective
of hidden and normal files (leading '.').
But a computer will always do what you tell it to but not what you want it
to.

No comments:

Post a Comment