tags:

views:

149

answers:

3

I have a flash drive device (/dev/sda1) mounted to /mnt on an embedded linux system (kernel 2.6.23). Using C how do I work out the size of the drive?

A: 

If you have no problem using external tools, exec this :

df -h | grep -i /dev/sda1

using popen, and parse the resulting line with strtok.

Geo
I am trying to avoid doing something like that. The application is running on an embedded platform and would require too much resource to do the above.
Andrew
`-h` is probably unnecessary here since the input will be read by program. `-i` is also redundant due to case-sensitivity. Other than that--a good LSB-conformant (i.e. portable) solution.
Pavel Shved
+4  A: 

On Linux, if you're not worried about portability (C doesn't know about drives, so any such specific code will be unportable), use statfs():

  struct statfs fsb;

  if(statfs("/dev/sda1", &fsb) == 0)
    printf("device has %ld blocks, each %ld bytes\n", fsb.f_blocks, fsb.f_bsize);
unwind
the above works if the path passed to statfs is "/mnt"
Andrew
+1  A: 

Read and parse a number in device's sysfs entry. In your case,

  1. Full device (all partitions and partition table): /sys/block/sda/size
  2. Logical partition on this device: /sys/block/sda/sda1/size

The device does not have to be mounted yet.

Alex B