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);
?
Open the directory using
opendir(), read the file names (readdir()) into an array, then do aqsort()on that array with its callback usingstat()to read in creation or modification dates, which you then in turn use to tellqsort()how to sort. Do not forget to close the directory usingclosedir()(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?