'Find the most recent file in a directory without reading all the contents of it

I'm trying to find out the latest file in a huge filesystem. One way to do this is to go through all directories - one at a time, read its contents, select the latest file etc.

The obvious drawback is I have to get all the files in a specific directory. I was wondering whether there was a 'magic' call in Python [1] which Unix supports to get just the latest file in a directory.

[1]. My application is in Python, but if a readymade solution doesnt exist in stdlib, please provide C (lanuage) alternatives using system calls. I'm willing to write a C-extension and make this work.

Thanks

update: I suppose I should offer an explanation on why an inotify type solution wont work for me. I was simply looking for a system call using Python/C which could give me the latest file. Yes, one could have inotify (or a similar overarching setup) which monitors FS changes but given a random directory how do I find the latest file is the essence of the question.



Solution 1:[1]

Have you considered using pyinotify which can watch a directory and subdirectories?
This might require your code to be threaded, say, a watcher thread that records the latest changes for the main thread to poll.

Alternatively, you could use popen and get the result of 'ls -t | head -1'

Solution 2:[2]

No portable API exists to do this in Unix. Most filesystems don't index files inside directories by their mtime (or ctime), so even if it did it probably wouldn't be any faster than doing it yourself.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Spaceghost
Solution 2 Glenn Maynard