Golang Listing Directory Contents and Sorting by File Modified Time

In this example we will be listing the contents of a directory in go and sorting by date.

To get the list of files we will use the ioutil.ReadDir function from the io/ioutil package. This function returns a slice sorted by file name which contains elements of os.FileInfo type which will enable us to get the last modified time.

To sort the files we will use the modification time with the sort package along with the After and Before functions from the time package.

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"sort"
)

func main() {
	files, err := ioutil.ReadDir(".")
	if err != nil {
		log.Fatal(err)
	}

	for _, file := range files {
		fmt.Println(file.Name(), file.Size(), file.ModTime())
	}

	// ascending
	sort.Slice(files, func(i,j int) bool{
	    return files[i].ModTime().Before(files[j].ModTime())
	})

	fmt.Println("\n-----------------------------------\n")

	for _, file := range files {
		fmt.Println(file.Name(), file.Size(), file.ModTime())
	}

	// descending
	sort.Slice(files, func(i,j int) bool{
	    return files[i].ModTime().After(files[j].ModTime())
	})

	fmt.Println("\n-----------------------------------\n")

	for _, file := range files {
		fmt.Println(file.Name(), file.Size(), file.ModTime())
	}
}