get system total disk space in go

To get the total disk space of the system in Go, we can use the syscall.Statfs() function from the syscall package. This function returns a syscall.Statfs_t struct which contains information about the file system.

Here's the code:

main.go
package main

import (
    "fmt"
    "syscall"
)

func main() {
    fs := syscall.Statfs_t{}
    err := syscall.Statfs("/", &fs)
    if err != nil {
        // handle error
    }
    total := fs.Blocks * uint64(fs.Bsize)
    fmt.Printf("Total disk space: %v bytes\n", total)
}
277 chars
17 lines

In the code above, we first create a syscall.Statfs_t struct to hold information about the file system. We then call syscall.Statfs("/", &fs) to fill the struct with information about the root file system. If we want to get information about a different file system, we can replace "/" with the path to that file system.

Finally, we calculate the total disk space by multiplying the number of blocks in the file system (fs.Blocks) by the block size (fs.Bsize). The result is in bytes. We then print the total disk space using fmt.Printf().

related categories

gistlibby LogSnag