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?