1
[Golang] Sort Files by Size
source link: http://siongui.github.io/2018/02/15/go-sort-files-by-size/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
[Golang] Sort Files by Size
February 15, 2018
Sort files in a directory by size in Go. The steps are:
- Use ioutil.ReadDir to get files in a directory (not including sub-directories).
- Use sort.Slice to sort the files by size.
The following are complete source code.
sortfile.go | repository | view raw
// Sort file by size package sortfile import ( "os" "sort" ) func SortFileBySize(files []os.FileInfo) { sort.Slice(files, func(i, j int) bool { return files[i].Size() < files[j].Size() }) }
sortfile_test.go | repository | view raw
package sortfile import ( "fmt" "io/ioutil" "os" "testing" ) func ExampleSortFileBySize(t *testing.T) { files, err := ioutil.ReadDir(os.Getenv("MY_DIR")) if err != nil { panic(err) } SortFileBySize(files) for _, file := range files { fmt.Println(file.Name()+": ", file.Size()) } }
If you want to know how to sort prior to Go 1.8, see [1].
If you want to find all files in a directory and all its sub-directories, see [2].
Tested on:
- Ubuntu Linux 17.10, Go 1.9.4
References:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK