gpt4 book ai didi

c - ioctl 和 hgreg 获取硬盘信息

转载 作者:行者123 更新时间:2023-11-30 17:43:12 26 4
gpt4 key购买 nike

我想从硬盘获取基本信息并将其打印出来。最重要的是物理扇区大小正确。

在过去的几个小时里,我一直在与 ioctl 斗争以获得我想要的东西,但我无法弄清楚。

我以前从未使用过ioctl,而且我似乎找不到关于您到底需要做什么的简单解释。

无论如何,我的代码看起来像这样

int main () {
FILE *driveptr;
int sectorsize;
struct hd_driveid hd;

driveptr=fopen("/dev/sda","r");

if (ioctl(driveptr,HDIO_GET_IDENTITY, &hd)!=0) {
printf("Hard disk model: %s\n",hd.model);
printf("Serial number: %s\n",hd.serial_no);
printf("Sector size: %i\n",hd.sector_bytes);
sectorsize=hd.sector_bytes;
} else {
printf("Error fetching device data.\n");
}
}

在编译器中它会抛出这些警告,它会编译,但打印时字符串为空。

gcc -o test source.c
source.c: In function ‘main’:
source.c:67:9: warning: passing argument 1 of ‘ioctl’ makes integer from pointer without a cast [enabled by default]
/usr/include/x86_64-linux-gnu/sys/ioctl.h:42:12: note: expected ‘int’ but argument is of type ‘struct FILE *’

我希望有人能向我解释一下出了什么问题!

最佳答案

而不是

if (ioctl(driveptr,HDIO_GET_IDENTITY, &hd)!=0) { 

你可能想要

if (ioctl(fileno(driveptr),HDIO_GET_IDENTITY, &hd)!= -1) { 
^^^^^^^ ^ ^^

因为ioctl的第一个参数需要是一个整数文件描述符而不是FILE *

fileno() 将为您提供来自 FILE * 的整数 fd。

另请注意,ioctl 在发生错误时返回 -1 并设置 errno。

阅读您正在使用的函数的手册页可能比发布到 StackOverflow 更快。

请参阅 ioctl 的手册页, fileno .

关于c - ioctl 和 hgreg 获取硬盘信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20291022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com