Home >Backend Development >Golang >How to Get Free Disk Space in Go: A Cross-Platform Guide?
Get Free Disk Space in Go
Finding the amount of free disk space is a common task in system administration. In Go, you can retrieve this information using the appropriate functions based on the operating system you are using.
POSIX Systems
On POSIX systems, you can use the sys.unix.Statfs function. This function takes the path to a file or directory as an argument and returns a unix.Statfs_t structure. The Bavail field of this structure represents the number of available blocks on the file system, while the Bsize field represents the size of each block in bytes. To calculate the free space in bytes, multiply these two values.
For example, to print the free space in bytes of the current working directory:
import ( "fmt" "golang.org/x/sys/unix" "os" ) func main() { var stat unix.Statfs_t wd, err := os.Getwd() if err != nil { panic(err) } if err := unix.Statfs(wd, &stat); err != nil { panic(err) } freeSpace := stat.Bavail * uint64(stat.Bsize) fmt.Println(freeSpace) }
Windows
On Windows, you can use the syscall package. This package provides access to the Windows API, which includes the GetDiskFreeSpaceEx function. This function takes the path to a drive as an argument and returns the free bytes available, the total number of bytes, and the total number of free bytes.
For example, to get the free space in bytes on the C: drive:
import ( "fmt" "golang.org/x/sys/windows" ) func main() { var freeBytesAvailable uint64 var totalNumberOfBytes uint64 var totalNumberOfFreeBytes uint64 err := windows.GetDiskFreeSpaceEx(windows.StringToUTF16Ptr("C:"), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes) if err != nil { panic(err) } fmt.Println(freeBytesAvailable) }
Cross-Platform Package
If you need a cross-platform solution, you can create a package that provides the functionality for both POSIX and Windows systems. The build tool in Go allows you to specify different behavior based on the operating system you are building for.
The above is the detailed content of How to Get Free Disk Space in Go: A Cross-Platform Guide?. For more information, please follow other related articles on the PHP Chinese website!