Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the size of mounted USB flash drive in C?

Tags:

c

linux

embedded

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?

like image 515
Andrew Avatar asked Sep 28 '09 14:09

Andrew


People also ask

How do I find the actual size of a flash drive?

Step 1. Check that Windows Properties shows that the drive has the size stated. From Explorer, navigate to the USB drive and right-click properties and check the Capacity shown. This should (approximately) match the stated drive capacity, which is usually printed on the outside of the drive, and / or on the box.

What is the capacity of the flash drive?

The first USB flash drive came on the market in 2000 with a storage capacity of 8 megabytes (MB). Drives now come in capacities ranging between 8 gigabytes (GB) and 1 terabyte (TB), depending on manufacturer, and future capacity levels are expected to reach 2 TB.


2 Answers

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);
like image 186
unwind Avatar answered Oct 09 '22 11:10

unwind


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.

like image 21
Alex B Avatar answered Oct 09 '22 10:10

Alex B