Linux C语言获取硬盘信息指南
Linux C语言获取硬盘信息指南
在Linux系统中,可以使用C语言编写程序来获取所有硬盘的信息。以下是一个示例程序:c#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <unistd.h>#include <linux/hdreg.h>
void print_disk_info(const char* disk_path) { int fd = open(disk_path, O_RDONLY | O_NONBLOCK); if (fd < 0) { perror('open'); return; }
struct hd_driveid hd; if (ioctl(fd, HDIO_GET_IDENTITY, &hd) < 0) { perror('ioctl'); close(fd); return; }
printf('Model: %s
', hd.model); printf('Serial Number: %s ', hd.serial_no); printf('Firmware Version: %s ', hd.fw_rev); printf('Capacity: %lld bytes ', (long long)hd.cyls * hd.heads * hd.sectors * hd.sector_bytes);
close(fd);}
int main() { FILE* fp = fopen('/proc/partitions', 'r'); if (fp == NULL) { perror('fopen'); return 1; }
char line[256]; while (fgets(line, sizeof(line), fp) != NULL) { unsigned int major, minor, blocks; if (sscanf(line, ' %u %u %u', &major, &minor, &blocks) == 3) { char disk_path[32]; sprintf(disk_path, '/dev/sd%c', 'a' + minor % 26); print_disk_info(disk_path); printf('
'); } }
fclose(fp); return 0;}
代码解释
这个程序分为两个主要部分:
-
print_disk_info函数: - 接收硬盘设备路径(/dev/sda等)作为参数。 - 使用open函数打开设备文件,并进行错误处理。 - 使用ioctl系统调用和HDIO_GET_IDENTITY请求获取硬盘的身份信息,包括型号、序列号、固件版本和容量。 - 打印获取到的硬盘信息。 - 关闭设备文件。 -
main函数: - 打开/proc/partitions文件,该文件包含系统中所有硬盘分区的信息。 - 逐行读取文件内容: - 使用sscanf函数解析每一行,提取主设备号、次设备号和块数信息。 - 根据次设备号计算硬盘设备路径,例如/dev/sda。 - 调用print_disk_info函数获取并打印该硬盘的信息。 - 关闭/proc/partitions文件。
编译和运行
- 将代码保存为
.c文件,例如disk_info.c。2. 使用 C 编译器编译代码:gcc disk_info.c -o disk_info3. 运行编译后的程序:./disk_info
运行程序后,你将看到系统中所有硬盘的详细信息,包括型号、序列号、固件版本和容量。
原文地址: https://www.cveoy.top/t/topic/fwIP 著作权归作者所有。请勿转载和采集!