如何从c中的路径获取文件所在的设备名称?

Meh*_*hdi 6 c linux device

假设我在 Linux 中有一个带有此路径的文件:

/path/to/file/test.mp3
Run Code Online (Sandbox Code Playgroud)

我想知道其设备的路径。例如,我想得到类似的东西:

/dev/sdb1
Run Code Online (Sandbox Code Playgroud)

我如何用C 编程语言做到这一点?

我知道执行此操作的终端命令,但我需要 C 函数来完成这项工作。

编辑:在问我的问题之前, 我已经阅读了这个问题。它没有具体提到 C 中的代码,它与 bash 的关系比与 C 语言的关系更大。

谢谢。

Zib*_*bri 5

我只需要在我正在编写的程序中使用它......

因此,我没有运行“df”并解析输出,而是从头开始编写它。

欢迎贡献!

回答这个问题:

首先使用 stat() 查找设备 inode,然后迭代并解析 /proc/self/mountinfo 以查找 inode 并获取设备名称。

/*
Get physical device from file or directory name.
By Zibri <zibri AT zibri DOT org>
https://github.com/Zibri/get_device
*/

#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <libgen.h>

int get_device(char *name)
{
  struct stat fs;

  if (stat(name, &fs) < 0) {
    fprintf(stderr, "%s: No such file or directory\n", name);
    return -1;
  }

  FILE *f;
  char sline[256];
  char minmaj[128];

  sprintf(minmaj, "%d:%d ", (int) fs.st_dev >> 8, (int) fs.st_dev & 0xff);

  f = fopen("/proc/self/mountinfo", "r");

  if (f == NULL) {
    fprintf(stderr, "Failed to open /proc/self/mountinfo\n");
    exit(-1);
  }

  while (fgets(sline, 256, f)) {

    char *token;
    char *where;

    token = strtok(sline, "-");
    where = strstr(token, minmaj);
    if (where) {
      token = strtok(NULL, " -:");
      token = strtok(NULL, " -:");
      printf("%s\n", token);
      break;
    }

  }

  fclose(f);

  return -1;
}

int main(int argc, char **argv)
{

  if (argc != 2) {
    fprintf(stderr, "Usage:\n%s FILE OR DIRECTORY...\n", basename(argv[0]));
    return -1;
  }
  get_device(argv[1]);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出只是设备名称。

例子:

$ gcc -O3 getdevice.c -o gd -Wall
$ ./gd .
/dev/sda4
$ ./gd /mnt/C
/dev/sda3
$ ./gd /mnt/D
/dev/sdb1
$
Run Code Online (Sandbox Code Playgroud)


use*_*016 5

使用此命令打印分区路径:

df -P <pathname> | awk 'END{print $1}'
Run Code Online (Sandbox Code Playgroud)


Sal*_*gar 4

您需要在文件路径上使用stat,并获取设备 IDst_dev 并将其与中的设备进行匹配/proc/partitions

阅读本文以了解如何解释st_devhttps://web.archive.org/web/20171013194110/http ://www.makelinux.net:80/ldd3/chp-3-sect-2