Home > Backend Development > Golang > How Can I Get Free Disk Space Information Across Windows, Linux, and macOS Using Go?

How Can I Get Free Disk Space Information Across Windows, Linux, and macOS Using Go?

Patricia Arquette
Release: 2024-12-16 19:16:12
Original
536 people have browsed it

How Can I Get Free Disk Space Information Across Windows, Linux, and macOS Using Go?

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

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

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!

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