elcuco
elcuco

Reputation: 9208

sorted glob in C/linux

I need to find the latest created/modified files in a directory. Basically what ls -t *.bla does. In C, not PHP, so this question does not help me - glob() - sort by date


This is an example of what no to do (forking a process is not cheap, it's lazy):

char filename[100];
FILE *f = popen("ls -1t /*.blabla");
fscanf(f, "%s", filename);
pclose(f);

?

Upvotes: 2

Views: 1195

Answers (1)

alk
alk

Reputation: 70941

Open the directory using opendir(), read the file names (readdir()) into an array, then do a qsort() on that array with its callback using stat() to read in creation or modification dates, which you then in turn use to tell qsort() how to sort. Do not forget to close the directory using closedir() (This could pimped to be even more effcient following the modification proposed in larsmans's comment below).

Finally after sorting is done, take the first/last array entry (depending on how you have sorted) and you are done.

If available you could also just use scandir() to have all this done at once (although you will not get around doing more stat() calls then necessary, as those need to be done in qsort's compare callback for this solution).

PS: Does anybody have an idea how to do this atomically?

Upvotes: 2

Related Questions