Sort
files, sizeIn Go programs we sometimes want to act upon the largest files first, and then proceed to the smallest ones. The opposite order is sometimes desired as well.
We can use the "sort" package, and call "sort.Sort
" on the FileInfo
array returned by Readdir
. With some custom logic, we can implement our sorting logic.
In this example, we specify a directory and assign this path to the "folder" variable. Then we use os.Open
and Readdir
to get the list of files in that directory.
ByFileSize
custom sorting type. It implements 3 methods from the sort interface
.ByFileSize
receives a FileInfo
array, and sorts each element (in Less) by the return value of Size()
.package main import ( "fmt" "os" "sort" "io/fs" ) // Access Size() in Less() to sort by file size. type ByFileSize []fs.FileInfo func (a ByFileSize) Len() int { return len(a) } func (a ByFileSize) Less(i, j int) bool { return a[i].Size() > a[j].Size() } func (a ByFileSize) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func main() { folder := "/Users/sam/programs/" // Read directory. dirRead, _ := os.Open(folder) dirFiles, _ := dirRead.Readdir(0) // Sort by file size. sort.Sort(ByFileSize(dirFiles)) // Write results. for dirIndex := range dirFiles { fileHere := dirFiles[dirIndex] fmt.Println(fileHere.Name(), fileHere.Size()) } }search-perls.txt 204568 merged-perls.txt 49157 ... program.php 196
Originally I wrote the file size sorting method to call os.Size
on each string
file name from a slice. This is inefficient, as the size is already available through FileInfo
.
FileInfo
array directly, avoiding further accesses to the operating system.Sorting files by their size (particularly in descending, low to high order) has been a recurring task in programming. A file's size can indicate its importance.