Golang Listing Directory Contents and Sorting by File Size

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

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

To sort the files we will use the sort package and compare the file sizes to arrange them in ascending or descending order.

package main

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

func SortFileSizeAscend(files []os.FileInfo) {
	sort.Slice(files, func(i, j int) bool {
		return files[i].Size() < files[j].Size()
	})
}

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

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

	SortFileSizeAscend(files)

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

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

	SortFileSizeDescend(files)

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