Reading Files From A Folder In Alphabetical Order


Alex.

Retired
Joined
Aug 24, 2005
Messages
4,616
Hi,

I've been having some trouble with a small file browser that looks for a specific type of files in a predefined folder. In order for things to make sense, I want to read the files in alphabetical order. Here's the code:

CODE
#include <dirent.h>
#include <sys/unistd.h>
extern int alphasort();

..

struct dirent** fileList;
int n = scandir(MAP_DIR, &fileList, NULL, alphasort);

for(i = 0; i < n; i++) {
// add fileList->d_name to a string linked list
}


The problem is that sometimes the files are read in proper alphabetical order, sometimes in reverse alphabetical order, and sometimes in a seemingly random manner. Sorry to ask such simple things, but I really lack experience in this part. Thanks a lot :)
 
That is pretty odd, I also just started using that scandir function and I haven't had any problems at all.
There are two things that jump out at me from the manpage for scandir. The first is that the strings are sorted using ascii ordering so upper case letters will appear before lower and punctuation could be anywhere. I know you're not dumb so it's unlikely to be that so the other thing is that alphasort() calls strcoll which depends on your system's locale setting for character ordering.

Ok so that wasn't much help was it, oh well, here's how I use it for your comparison:

CODE

int level_file(const struct dirent *filename)
{
if(0 == strncmp("level_", filename->d_name, 6))
return 1;
else
return 0;
}

int level_menu(SDL_Surface *surface, char *datadir)
{
struct dirent **levels = NULL;
char **level_names = NULL;
int nlevels = 0;

nlevels = scandir(datadir, &levels, &level_file, &alphasort);
/* do some stuff with the levels.d_name and datadir*/
for(i = 0; i < nlevels; ++i)
free(&levels);

free(levels);

return 0;
}



The only real difference I see is that I pass alphasort as a reference but I doubt it would be something like that if you can get yours to compile.

Hope this helps in some small way,

Charlie
 
Thanks for the help charlie, it seems to work fine now. I removed some old code that conflicted with some things, and all is good. I didn't know about that nice method to check if a file should be read or not, thanks for that as well :)
 
Back
Top