Please be aware that readdir() and opendir() etc will return sorted directory listings automatically on some operating systems, whilst others it will not.
On later versions of windows, you can usually be guaranteed alphabetically sorted file listings from readdir(), and on Linux there is no such guarantee. If you require any particular sort order you should read the results to an array and use asort() or rsort() on it, or similar, to get the results into the order you need.