![](/img/trans.png)
[英]how to get partition number and block device name seperating from a path in c program?
[英]How to get device name on which a file is located from its path in c?
假设我在 Linux 中有一个带有此路径的文件:
/path/to/file/test.mp3
我想知道其设备的路径。 例如,我想得到类似的东西:
/dev/sdb1
我如何用C 编程语言做到这一点?
我知道执行此操作的终端命令,但我需要 C 函数来完成这项工作。
编辑:在问我的问题之前,我已经阅读了这个问题。 它没有具体提到 C 中的代码,它与 bash 的关系比与 C 语言的关系更大。
谢谢。
我只是需要在我正在编写的程序中使用它...
因此,我没有运行“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;
}
输出只是设备名称。
示例:
$ gcc -O3 getdevice.c -o gd -Wall
$ ./gd .
/dev/sda4
$ ./gd /mnt/C
/dev/sda3
$ ./gd /mnt/D
/dev/sdb1
$
使用此命令打印分区路径:
df -P <pathname> | awk 'END{print $1}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.