Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux C programming: How to get a device's partition infomation?

Tags:

c

linux

I'm new to Linux c programming, is there any API that can get a device's partition information?

like image 337
bright Avatar asked Dec 29 '11 03:12

bright


People also ask

How do I see partition details in Linux?

The best way to check disk partition in Linux is using fdisk command. It is a text-based utility for viewing and manipulating disk partitions. Typing fdisk -l at the command prompt will list all of the partitions on your Linux system. You can also use the fdisk command to create, delete, or resize partitions.


2 Answers

Akash Rawal's answer is pretty close. A good way is to use libblkid.

This is an example to get uuid of a partition: Using libblkid to find UUID of a partition.

I combined the code shown above and examples in libblkid reference menu and generate below working program:

#include <stdio.h>
#include <string.h>
#include <err.h>
#include <blkid/blkid.h>


int main (int argc, char *argv[]) {
   blkid_probe pr = blkid_new_probe_from_filename(argv[1]);
   if (!pr) {
      err(1, "Failed to open %s", argv[1]);
   }

   // Get number of partitions
   blkid_partlist ls;
   int nparts, i;

   ls = blkid_probe_get_partitions(pr);
   nparts = blkid_partlist_numof_partitions(ls);
   printf("Number of partitions:%d\n", nparts);

   if (nparts <= 0){
      printf("Please enter correct device name! e.g. \"/dev/sdc\"\n");
      return;
   }

   // Get UUID, label and type
   const char *uuid;
   const char *label;
   const char *type;

   for (i = 0; i < nparts; i++) {
      char dev_name[20];

      sprintf(dev_name, "%s%d", argv[1], (i+1));

      pr = blkid_new_probe_from_filename(dev_name);
      blkid_do_probe(pr);

      blkid_probe_lookup_value(pr, "UUID", &uuid, NULL);

      blkid_probe_lookup_value(pr, "LABEL", &label, NULL);

      blkid_probe_lookup_value(pr, "TYPE", &type, NULL);

      printf("Name=%s, UUID=%s, LABEL=%s, TYPE=%s\n", dev_name, uuid, label, type);

   }

   blkid_free_probe(pr);

   return 0;
}

Usage:

gcc -o getuuid getuuid.c -lblkid
sudo ./getuuid /dev/sdc
Number of partitions:1
Name=/dev/sdc1, UUID=754A-CE25, LABEL=KINGSTON, TYPE=vfat
like image 141
Peter Avatar answered Nov 10 '22 08:11

Peter


You could have a look at /sys/block/sd?/ where there are many pseudo-files telling you about some partition parameters.

like image 38
glglgl Avatar answered Nov 10 '22 08:11

glglgl