如何使用 statvfs 查找磁盘名称?

How do I find disk name with statvfs?

我正在使用 statvfs 收集有关特定文件的信息。我也想获得磁盘 name/partition(如 /dev/sdb1/dev/media 等)。但是 statvfs 结构似乎不提供此类数据。我在哪里可以找到它?

使用getmntent():

SYNOPSIS

   #include <stdio.h>
   #include <mntent.h>

   FILE *setmntent(const char *filename, const char *type);

   struct mntent *getmntent(FILE *stream);

   int addmntent(FILE *stream, const struct mntent *mnt);

   int endmntent(FILE *streamp);

   char *hasmntopt(const struct mntent *mnt, const char *opt);

...

DESCRIPTION

...

The mntent structure is defined in as follows:

struct mntent {
    char *mnt_fsname;   /* name of mounted filesystem */
    char *mnt_dir;      /* filesystem path prefix */
    char *mnt_type;     /* mount type (see mntent.h) */
    char *mnt_opts;     /* mount options (see mntent.h) */
    int   mnt_freq;     /* dump frequency in days */
    int   mnt_passno;   /* pass number on parallel fsck */
};

例如:

FILE *fp = setmntent( "/etc/mtab", "r" );
for ( ;; )
{
    struct mntent *me = getmntent( fp );
    if ( NULL == me )
    {
        break;
    }

    ...
}

endmntent( fp );

给定一个文件名,您必须进行一些编码以使文件名与文件系统挂载点相匹配。最简单的方法可能是将文件 struct statvfs 中的 f_fsid 字段与通过调用文件系统的挂载点上的 statvfs() 获得的挂载文件系统的 f_fsid 相匹配getmntent().

返回的 struct mntent