Cross-Platform Disk Space Retrieval in Go
In this article, we address the challenge of obtaining free disk space information, covering Windows, Linux, and Mac platforms using the Go programming language.
Problem Statement
The goal is to replicate the output of the widely used Unix command df -h, which provides details on free and total storage space for volumes. This functionality must be adaptable to diverse operating systems and implemented in Go.
Solution
POSIX Systems (Linux, Mac)
On POSIX-based systems (Unix-like operating systems such as Linux and Mac), the sys.unix.Statfs package is utilized. This package contains the Statfs function, which returns a data structure representing file system statistics. The following code snippet demonstrates its usage:
import "golang.org/x/sys/unix" import "os" var stat unix.Statfs_t wd, err := os.Getwd() unix.Statfs(wd, &stat) // Available blocks * size per block = available space in bytes fmt.Println(stat.Bavail * uint64(stat.Bsize))
Windows Systems
For Windows systems, the syscall package provides access to Windows system calls. The following code snippet demonstrates its usage:
import "golang.org/x/sys/windows" var freeBytesAvailable uint64 var totalNumberOfBytes uint64 var totalNumberOfFreeBytes uint64 err := windows.GetDiskFreeSpaceEx(windows.StringToUTF16Ptr("C:"), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes)
Cross-Platform Package
Based on the provided solutions, users are encouraged to develop a cross-platform package that encapsulates this functionality. This package should abstract away the underlying platform-specific implementations and provide a consistent interface for retrieving free disk space information regardless of the operating system.
The above is the detailed content of How Can I Get Free Disk Space Information Across Windows, Linux, and macOS Using Go?. For more information, please follow other related articles on the PHP Chinese website!