c - 如何确定 C 中 Linux 上给定文件的安装路径?

标签 c linux

我有一个任意文件,我想为其确定挂载点。假设它是/mnt/bar/foo.txt,除了“正常”的 Linux 挂载点之外,我们还有以下挂载点:

[某些设备安装到] ->/mnt/bar [一些设备安装到] ->/mnt/other

我查看了 stat() 和 statvfs()。 statvfs() 可以为我提供文件系统 ID,stat 可以为我提供设备的 ID,但这些都不能真正关联到挂载点。

我想我必须做的是在任意文件上调用 readlink(),然后通读/proc/mounts,确定哪个路径与文件名最匹配。这是一个好方法,还是我错过了一些很棒的 libc 函数?

最佳答案

您可以使用 getfsent 的组合来完成遍历设备列表,stat检查您的文件是否在该设备上。

#include <fstab.h>    /* for getfsent() */
#include <sys/stat.h> /* for stat() */

struct fstab *getfssearch(const char *path) {
    /* stat the file in question */
    struct stat path_stat;
    stat(path, &path_stat);

    /* iterate through the list of devices */
    struct fstab *fs = NULL;
    while( (fs = getfsent()) ) {
        /* stat the mount point */
        struct stat dev_stat;
        stat(fs->fs_file, &dev_stat);

        /* check if our file and the mount point are on the same device */
        if( dev_stat.st_dev == path_stat.st_dev ) {
            break;
        }
    }

    return fs;
}

请注意,为简洁起见,此处没有错误检查。此外,getfsent 不是 POSIX 函数,但它是一个使用非常广泛的约定。它适用于甚至不使用 /etc/fstab 的 OS X。它也不是线程安全的。

关于c - 如何确定 C 中 Linux 上给定文件的安装路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40659638/

相关文章:

c - 如何计时人完成 C 程序的速度?

c - 在c中的文件中搜索

linux - curl 和 cookies - 命令行工具

linux - 如何编写 shell 脚本在没有 ssh 的情况下在多台远程机器上运行脚本?

php - 如何通过 PHP 中的 SAFE MODE 限制?

database - 在 Linux 上索引大型数据集的最便宜方法(最好使用 sphinx)

linux - 其中一些 AWK 命令有什么作用?

c - 程序不显示链接列表,但在c中创建链接列表

c - 如何安装 mcrypt 并将 mcrypt.h 添加到我的 C 程序文件中?

c - 修改 printf 输出