hakk

software development, devops, and other drivel
Tree lined path

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 os.ReadDir function from the os 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/fs"
	"log"
	"os"
	"sort"
)

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func printFiles(files []fs.DirEntry) {
	for _, file := range files {
		fileInfo, err := file.Info()
		checkErr(err)
		fmt.Println(file.Name(), fileInfo.Size(), fileInfo.ModTime())
	}
}

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

	printFiles(files)
	
	// ascending
	sort.Slice(files, func(i,j int) bool{
		fileI, err := files[i].Info()
		checkErr(err)
		fileJ, err := files[j].Info()
		checkErr(err)
	    return fileI.ModTime().Before(fileJ.ModTime())
	})

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

	printFiles(files)

	// descending
	sort.Slice(files, func(i,j int) bool{
		fileI, err := files[i].Info()
		checkErr(err)
		fileJ, err := files[j].Info()
		checkErr(err)
	    return fileI.ModTime().After(fileJ.ModTime())
	})

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

	printFiles(files)
}