rodolfo gomes dias
rodolfo gomes dias

Reputation: 173

How to programmatically discover the filesystem without mounting the device (like "fdisk -l")

I need to find a system call in linux to discover the filesystem of a connected pendrive in my application. I found out that the 'fdisk -l' do the job however I need now to discover how this happens. I wasn't capable to discover reading the fdisk code, the only certain think is that:

  1. The structs statfs or statvfs are not used;
  2. The fdisk doesn't need to mount the device to find the filesystem;

Obs: My application is written in C++ and is running in a embedded linux system.

Upvotes: 2

Views: 2755

Answers (2)

syplex
syplex

Reputation: 1167

The command fdisk -l displays the file system represented by the System ID byte. This byte is in the Partition Table which is inside the Master Boot Record (MBR). The MBR is usually stored on the first cylinder on the first hard drive (although any hard drive can have an MBR).

I would think you could simply use the open and read system calls to read the MBR from the disk assuming the user running your program has permission:

char buf[446];
int fd = open("/dev/hda", O_RDONLY);
read(fd, buf, 446);

Look over the MBR Format and then read out the partition table to get the System ID bytes. Here's a list of types for the System ID byte.

I am only aware of how fdisk on Linux works, and last time I checked it didn't support GPT or any other partitioning formats. So this answer is relevant only to the classical MBR format.

Upvotes: 2

John Bartholomew
John Bartholomew

Reputation: 6586

You can use libblkid from util-linux to do this. The source distribution includes a sample which lists the partitions on a specified device, including filesystem type.

Upvotes: 1

Related Questions