简体   繁体   中英

In Linux in C/C++ how to determine filesystem type of a mounted or unmounted partition

# blkid /dev/sdX gives the filesystem type of the partition whether mounted or unmounted. How can I do it from C/C++ with out invoking a system call and parsing the out put? How can I do it programatically? Is there any blkid-dev package?

You always can use the blkid libraries (for ubuntu it's as easy as installing libblkid-dev). And for the real usage see: https://github.com/fritzone/sinfonifry/blob/master/plugins/disk_status/client/disk_status.cpp (sorry for advertising code from my own repository, but it has exactly this functionality developed there). And do not forget, that you will need to run the application with sudo in order to have full access to the disk.

For mounted partitions, your C++ program could read sequentially and parse the /proc/self/mounts pseudo-file, see proc(5)

For unmounted partitions, they could contain anything (including no file system at all, or swap data, or raw data - eg for some database system). So the question may even be meaningless. You might popen some file -s command.

You should study the source code of /bin/mount since it is free software (and it does similar things for the auto case). You may want to use libmagic(3) (which is used by file(1) command)

For mounted partition, instead of reading /proc/self/mounts, you can do that (assuming you know the path where the partition is mounted):

#include <sys/vfs.h>
#include <stdio.h>
#include <linux/magic.h>

static const struct {
    unsigned long magic;
    const char   *type;
} types[] = {
    {EXT4_SUPER_MAGIC, "ext4"},
    {TMPFS_MAGIC, "tmpfs"},
};


const char *get_type(unsigned long magic) {
    static const char * unkown="unkown";
    unsigned int i;

    for (i=0; i < sizeof(types)/sizeof(types[0]); i++)
        if (types[i].magic == magic)
            return types[i].type;

    return unkown;
}

void main() {

    struct statfs buf;

    statfs("/", &buf);
    printf("/ is %s\n", get_type((unsigned long)buf.f_type));

    statfs("/tmp", &buf);
    printf("/tmp is %s\n", get_type((unsigned long)buf.f_type));    
}

In my case it displays:

/ is ext4
/tmp is tmpfs

For more details see

man statfs

You can obviously add all the types you need. They are listed by the statfs manpage. It is said that statfs is deprecated, by I don't know of another call that would return the filesystem type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM