linux c 判断磁盘挂载
时间: 2023-12-23 20:02:50 浏览: 397
以下是在Linux C中判断磁盘是否挂载的方法:
1. 使用statfs函数获取文件系统信息,如果返回值为0,则表示该文件系统已经挂载,否则未挂载。
```c
#include <sys/vfs.h>
#include <stdio.h>
int main() {
struct statfs s; int ret = statfs("/mnt/disk", &s);
if (ret == 0) {
printf("The disk is mounted.\n");
} else {
printf("The disk is not mounted.\n");
}
return 0;
}
```
2. 使用df命令获取文件系统信息,然后解析输出结果,如果挂载点为指定目录,则表示该文件系统已经挂载,否则未挂载。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 1024
int main() {
FILE *fp;
char buf[MAX_LINE];
char cmd[MAX_LINE];
char *mount_point = "/mnt/disk";
sprintf(cmd, "df %s", mount_point);
if ((fp = popen(cmd, "r")) == NULL) {
printf("Error: popen failed.\n");
exit(1);
}
while (fgets(buf, MAX_LINE, fp) != NULL) {
if (strstr(buf, mount_point) != NULL) {
printf("The disk is mounted.\n");
pclose(fp);
return 0;
}
}
printf("The disk is not mounted.\n");
pclose(fp);
return 0;
}
```
阅读全文