Reputation: 984
I'm trying to get a directory listing and sort it into last modified time order using Vala.
I've got the directory listing part into a List < FileInfo >. But I cannot figure out how to sort the list.
Upvotes: 1
Views: 545
Reputation: 1421
This is done via the the sort(CompareFunc<G> compare_func)
method in the List
class. You can read more about it here.
A basic example for strings would be:
list.sort((a,b) => {
return a.ascii_casecmp(b);
});
The return value of the function passed to sort()
is the same as the ISO C90 qsort(3)
function:
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
As you're interested in modify time, the FileAttribute
you're looking for is TIME_MODIFIED which you would get by calling the appropriate get_attribute_*
method of FileInfo
.
Upvotes: 4
Reputation: 984
static int main (string[] args) {
var directory = File.new_for_path ("/var/db/pkg");
var glib_list = new GLib.List<FileInfo> ();
try {
var enumerator = directory.enumerate_children (FileAttribute.TIME_MODIFIED, FileQueryInfoFlags.NOFOLLOW_SYMLINKS);
FileInfo file_info;
while ((file_info = enumerator.next_file()) != null) {
glib_list.append(file_info);
}
} catch(Error e) {
stderr.printf ("Error: %s\n", e.message);
}
// Lets sort it.
CompareFunc<FileInfo> my_compare_func = (a, b) => {
long c = a.get_modification_time().tv_sec;
long d = b.get_modification_time().tv_sec;
return (int) (c > d) - (int) (c < d);
};
glib_list.sort(my_compare_func);
foreach (FileInfo file_info in glib_list) {
stdout.printf ("%s\n", file_info.get_name());
}
return 0;
}
Upvotes: 0