How do I find the size of mounted USB flash drive in C?
10,451
Solution 1
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("/mnt", &fsb) == 0)
printf("device has %ld blocks, each %ld bytes\n", fsb.f_blocks, fsb.f_bsize);
Solution 2
Read and parse a number in device's sysfs entry. In your case,
- Full device (all partitions and partition table):
/sys/block/sda/size
- Logical partition on this device:
/sys/block/sda/sda1/size
The device does not have to be mounted yet.
Author by
Andrew
Updated on June 19, 2022Comments
-
Andrew almost 2 years
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?
-
Andrew over 14 yearsI 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.
-
P Shved over 14 years
-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.