繁体   English   中英

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

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

# 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运行应用程序才能完全访问磁盘。

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

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

您应该研究/bin/mount的源代码,因为它是免费软件(对于auto案例它也做类似的事情)。 您可能要使用libmagic(3) (由file(1)命令使用)

对于已安装的分区,您可以执行以下操作(而不是读取/ 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已过时,因为我不知道会返回文件系统类型的另一个调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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