运行结果如下
jackie@Ubuntu:~/work/0602$ sudo ./a.out /dev/sda
/dev/sda
3907029168,2000398934016
//BLKGETSIZE64 获取空间大小 (bytes)
//BLKGETSIZE 获取块数量 * 512 = 空间大小 (在vmware esxi环境下这个不能用,还不知道原因)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <linux/fs.h>
#include <sys/ioctl.h>
int main(int argc,char *argv[]){
int fd;
off_t space,space64;
fd = open(argv[1], O_RDONLY);
printf("%s
",argv[1]);
if(fd == -1) {
printf("main: open device failed
");
return -1;
}
if (ioctl(fd, BLKGETSIZE64, &space64)) {
perror("Get free space64 failed");
close(fd);
return 1;
}
if (ioctl(fd, BLKGETSIZE, &space)) {
perror("Get free space failed");
close(fd);
return 1;
}
printf("%lu,%lu
",space,space64);
close(fd);
}