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

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

Mary-Kate Olsen
Release: 2024-12-31 16:59:10
Original
627 people have browsed it

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

Retrieving Free Disk Space in Go Across Multiple Platforms

In this article, we explore a solution to dynamically retrieve the free and total size of a storage volume using Go, regardless of the operating system (Windows, Linux, Mac). This solution eliminates the need for external commands like df -h or manual calculations.

For POSIX-based systems, we leverage the sys.unix.Statfs function to access the Statfs_t structure. For instance, to obtain the free space for the current working directory in bytes:

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))
Copy after login

In the case of Windows, we take the syscall approach. Here's an updated example using the newer sys/windows package:

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

var freeBytesAvailable uint64
var totalNumberOfBytes uint64
var totalNumberOfFreeBytes uint64

err := windows.GetDiskFreeSpaceEx(windows.StringToUTF16Ptr("C:"),
    &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes)
Copy after login

Don't hesitate to extend these examples into a cross-platform package for broader usage. For guidance on cross-platform implementation, consult the build tool's help documentation.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template