在Linux的C/C++中,如何确定已安装或未安装分区的文件系统类型

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

本文关键字:安装 分区 类型 文件系统 何确定 Linux C++      更新时间:2023-10-16

# blkid /dev/sdX给出分区的文件系统类型,无论是已安装还是已卸载。如何从C/C++中调用系统调用并解析输出?我怎样才能用程序来做?有blkid-dev包裹吗?

您总是可以使用blkid库(对于ubuntu,它就像安装libblkid-dev一样简单)。有关实际用途,请参阅:https://github.com/fritzone/sinfonifry/blob/master/plugins/disk_status/client/disk_status.cpp(很抱歉从我自己的存储库中发布代码,但它正是在那里开发的功能)。不要忘记,您需要使用sudo运行应用程序才能完全访问磁盘。

对于挂载的分区,您可以这样做,而不是读取/proc/self/mounts(假设您知道挂载分区的路径):

#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 %sn", get_type((unsigned long)buf.f_type));
    statfs("/tmp", &buf);
    printf("/tmp is %sn", get_type((unsigned long)buf.f_type));    
}

在我的情况下,它显示:

/ is ext4
/tmp is tmpfs

有关更多详细信息,请参阅

man statfs

很明显,您可以添加所需的所有类型。它们由statfs手册页列出。据说statfs已被弃用,因为我不知道还有哪个调用会返回文件系统类型。

对于挂载的分区,C++程序可以按顺序读取并解析/proc/self/mounts伪文件,请参阅proc(5)

对于已卸载的分区,它们可以包含任何内容(包括根本没有文件系统、交换数据或原始数据,例如某些数据库系统)。因此,这个问题甚至可能毫无意义。您可以popen某个file -s命令。

你应该研究/bin/mount的源代码,因为它是自由软件(它对auto的情况做了类似的事情)。您可能想要使用libmagic(3)(由文件(1)命令使用)