How to determine the size of a raw device (in a C programm)

来源:百度文库 编辑:神马文学网 时间:2024/06/03 11:12:05

How to determine the size of a raw device (in a C programm)

Your Problem

You are writing some sort of C or C++ program. You want to determine thesize of a block device, for example of /dev/hda2. You are usinglseek or lseek64 but you run into one problem:

lseek does not work for raw devices like /dev/raw/raw1 sincethey are character devices. Seeking works, but always returns 0.

The Solution

The following solution is tested on Kernel 2.6.4 (SuSE 9.1): Use theioctl() method BLKGETSIZE on the device:

#include #include main(int argc, char **argv){int fd;unsigned long numblocks=0;fd = open(argv[1], O_RDONLY);ioctl(fd, BLKGETSIZE, &numblocks);close(fd);printf("Number of blocks: %lu, this makes %.3f GB\n",numblocks,(double)numblocks * 512.0 / (1024 * 1024 * 1024));}

A few notes to the example

  • In order to keep the example simple, there are no error checks.
  • Use at your own risk!

Running the example

Write the upper code into a file getsize.c and compile it:

> gcc -o getsize getsize.c

Now you can run it (as root):

# ./getsize /dev/raw/raw2Number of blocks: 312581808, this makes 149.051 GB# ./getsize /dev/hddNumber of blocks: 90069840, this makes 42.949 GB