SimplifyC++ Article
Hardware Access with Rust Retrieving Hard Drive Information (Windows)
Hardware Access with Rust: Retrieving Hard Drive Information (Windows)
Rust example using the system_diskinfo crate to retrieve hard drive data, including the physical serial number:
use system_diskinfo::{drive_serial_number, drive_model, drive_size, drive_name};
fn main() { // Get information for the system drive (usually C:\ on Windows) match drive_serial_number() { Ok(serial_number) => println!("Drive Serial Number: {}", serial_number), Err(e) => eprintln!("Error getting serial number: {}", e), }
match drive_model() { Ok(model) => println!("Drive Model: {}", model), Err(e) => eprintln!("Error getting model: {}", e), }
match drive_size() { Ok(size) => println!("Drive Size: {} GB", size / 1024 / 1024 / 1024), // Convert bytes to GB Err(e) => eprintln!("Error getting size: {}", e), }
match drive_name() { Ok(name) => println!("Drive Name: {}", name), Err(e) => eprintln!("Error getting name: {}", e), }}
Explanation:
Import: Import the necessary functions from the
system_diskinfocrate.Retrieve Information:
Call
drive_serial_number(),drive_model(),drive_size(), anddrive_name()to fetch the respective information.These functions return a
Resulttype, which can be eitherOk(containing the data) orErr(indicating an error).
Handle Results:
Use
matchto handle both success and error cases:
If the result is
Ok, print the retrieved information.If the result is
Err, print an error message.
Drive Size Conversion: Convert the drive size from bytes to gigabytes (GB) for better readability.
Key Points:
system_diskinfoCrate: This crate simplifies the process of accessing disk information on Windows systems. It abstracts away the low-level WinAPI calls, making it easier to use in Rust.Error Handling: Rust's
Resulttype and thematchexpression ensure robust error handling, making your code more reliable.Platform Specificity: Note that the
system_diskinfocrate is currently designed for Windows. If you need to get disk information on other platforms (like Linux or macOS), you'll need to use different libraries or system calls.
To use this example:
Add Dependency: Add the
system_diskinfocrate to your project'sCargo.tomlfile:[dependencies]system_diskinfo = "0.1.3" // Or the latest versionRun: Compile and run the Rust code. It should print the serial number, model, size, and name of your system's hard drive.
What did you think?
Sign in to react or comment.
Comments
0No comments yet.