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

问题描述 投票:0回答:4

# blkid /dev/sdX
给出分区的文件系统类型,无论是已安装还是已卸载。如何在不调用系统调用和解析输出的情况下从 C/C++ 执行此操作?我怎样才能以编程方式做到这一点?有
blkid-dev
套餐吗?

c++ linux mount
4个回答
6
投票

您始终可以使用

blkid
库(对于 ubuntu,就像安装 libblkid-dev 一样简单)。对于真正的用法,请参阅:https://github.com/fritzone/sinfonifry/blob/master/plugins/disk_status/client/disk_status.cpp(很抱歉来自我自己的存储库的广告代码,但它正是具有此功能)那里发展起来的)。不要忘记,您需要使用 sudo 运行应用程序才能完全访问磁盘。


2
投票

对于 mounted 分区,您可以这样做,而不是读取 /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 %s\n", get_type((unsigned long)buf.f_type));

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

就我而言,它显示:

/ is ext4
/tmp is tmpfs

更多详情请参阅

man statfs

您显然可以添加您需要的所有类型。它们由 statfs 联机帮助页列出。 据说 statfs 已被弃用,因为我不知道还有其他调用会返回文件系统类型。


0
投票

对于已挂载的分区,您的 C++ 程序可以顺序读取并解析

/proc/self/mounts
伪文件,请参阅 proc(5)

对于未安装的分区,它们可以包含任何内容(包括根本没有文件系统,或交换数据,或原始数据 - 例如对于某些数据库系统)。所以这个问题甚至可能毫无意义。您可能会

popen
一些
file -s
命令。

您应该研究

/bin/mount
的源代码,因为它是免费软件(并且它对
auto
案例做了类似的事情)。您可能想使用 libmagic(3) (由 file(1) 命令使用)


0
投票

对于已安装/未安装分区:

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

// gcc get_filesystem.c -o get_filesystem -lblkid

void main(void)
{    
    const char *dev_part = "/dev/sda5"; // Partition name
    const char *fs = NULL;
    blkid_probe pr;


    pr = blkid_new_probe_from_filename(dev_part);

    if (!pr) {
        printf("Error: pr!\n");
        return;
    }
   
    blkid_probe_enable_partitions(pr, 1);
    blkid_do_fullprobe(pr);
    blkid_probe_lookup_value(pr, "TYPE", &fs, NULL);

    printf("Filesystem: %s\n", fs);

    blkid_free_probe(pr);

    return;
}
© www.soinside.com 2019 - 2024. All rights reserved.