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 the size of a block device, for example of /dev/hda2. You are using lseek or lseek64 but you run into one problem:

lseek does not work for raw devices like /dev/raw/raw1 since they 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 the ioctl() method BLKGETSIZE on the device:

#include <fcntl.h>
#include <linux/fs.h>

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

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/raw2
Number of blocks: 312581808, this makes 149.051 GB
# ./getsize /dev/hdd
Number of blocks: 90069840, this makes 42.949 GB

Keywords: rawdevice raw device blocksize size determine ioctl blkgetsize lseek lseek64 linux26   Author: Mathias Kettner

Tauschzone MK