2

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);

?

Community
  • 1
  • 1
elcuco
  • 8,948
  • 9
  • 47
  • 69

1 Answers1

2

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?

alk
  • 69,737
  • 10
  • 105
  • 255
  • 3
    This is expensive too due to all the `stat` calls. Better set up an array of `struct stat`/filename pairs and sort that. – Fred Foo Nov 06 '11 at 17:02
  • You could also make it more efficient knowing that you only need the last few modified files (no need to sort the whole list). Still, we don't even know if efficiency matters here so this is a fine. Just tell us where qsort is defined (what header and library do we need?) – David Grayson Nov 06 '11 at 17:10
  • @David Grayson `qsort()` should be prototyped in `stdlib.h`. – alk Nov 06 '11 at 17:14
  • @DavidGrayson see http://stackoverflow.com/questions/5102863/how-to-sort-files-in-some-directory-by-the-names-on-linux – elcuco Nov 07 '11 at 08:15