Golang Listing Directory Contents and Sorting by File Name

Listing the contents of a directory in go and sorting by filename.

To get the list of file we will use the ReadDir function from the ioutil package.

To sort the files we will use the sort package to arrange the filenames alphabetically ascending or descending.

package main

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

// this is the default sort order of golang ReadDir
func SortFileNameAscend(files []os.FileInfo) {
	sort.Slice(files, func(i, j int) bool {
		return files[i].Name() < files[j].Name()
	})
}

func SortFileNameDescend(files []os.FileInfo) {
	sort.Slice(files, func(i, j int) bool {
		return files[i].Name() > files[j].Name()
	})
}

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

	//SortFileNameAscend(files)

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

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

	SortFileNameDescend(files)

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