Home >Backend Development >Golang >How Can I Get Free Disk Space Information in Go Across Different Operating Systems?

How Can I Get Free Disk Space Information in Go Across Different Operating Systems?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-27 08:00:15510browse

How Can I Get Free Disk Space Information in Go Across Different Operating Systems?

Retrieving Free Disk Space with Go

Getting the amount of free disk space is essential for managing storage on various platforms. In Go, cross-platform disk space retrieval requires different approaches depending on the underlying operating system.

POSIX Systems

For POSIX systems, which include Linux and Mac, the sys.unix.Statfs function provides access to disk usage information. Here's how to use it:

import "golang.org/x/sys/unix"
import "os"

wd, _ := os.Getwd()

var stat unix.Statfs_t
unix.Statfs(wd, &stat)

freeSpace := stat.Bavail * uint64(stat.Bsize)

Windows Systems

On Windows, the syscall package offers the GetDiskFreeSpaceEx function to retrieve free disk space data:

import "golang.org/x/sys/windows"

var freeBytesAvailable uint64
var totalNumberOfBytes uint64
var totalNumberOfFreeBytes uint64
windows.GetDiskFreeSpaceEx("C:", &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes)

Cross-Platform Package

If you require cross-platform functionality for retrieving free disk space, you can create a custom Go package that abstracts the platform-specific implementations. This package can provide a consistent interface across different operating systems, making it easier to handle disk space management in your applications.

The above is the detailed content of How Can I Get Free Disk Space Information in Go Across Different Operating Systems?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn