如何获取系统下目录的文件系统类型
最近看到一个问题,如何获取当前系统的文件类型?
这个时候就要介绍下/proc/mounts
文件:这个文件以/etc/mtab
文件的格式给出当前系统所安装的文件系统信息。同时也能反映出任何手工安装从而在/etc/mtab
文件中没有包含的文件系统。
我们可以通过cat /proc/mounts
查看挂载文件系统的状态。
root@firefly:~# cat /proc/mounts
sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0
proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0
udev /dev devtmpfs rw,nosuid,relatime,size=1960196k,nr_inodes=490049,mode=755 0 0
devpts /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000 0 0
tmpfs /run tmpfs rw,nosuid,noexec,relatime,size=393192k,mode=755 0 0
/dev/mmcblk1p7 /root-ro ext4 ro,relatime,data=ordered 0 0
/dev/mmcblk1p8 /userdata ext4 rw,relatime,data=ordered 0 0
overlayroot / overlay rw,relatime,lowerdir=/root-ro,upperdir=/userdata/rootfs_overlay,workdir=/userdata/rootfs_overlay-workdir/_ 0 0
securityfs /sys/kernel/security securityfs rw,nosuid,nodev,noexec,relatime 0 0
tmpfs /dev/shm tmpfs rw,nosuid,nodev 0 0
tmpfs /run/lock tmpfs rw,nosuid,nodev,noexec,relatime,size=5120k 0 0
mounts文件包含6列
- Device mount的设备
- Mount Point 挂载点,也就是挂载的路径
- File System Type 文件系统类型,如ext4、xfs等
- Options 挂载选项,包括读写权限等参数
- 无用内容,保持内容和/etc/fstab格式一致
- 无用内容,保持内容和/etc/fstab格式一致
下面写个程序提取下设备名,挂载目录,文件系统类型等参数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MOUNTS_INFO "/proc/mounts"
typedef struct
{
char devName[32];
char dirName[16];
char fsType[16];
char authority[16];
}PartitionInfo;
int getPartitionInfo(char *pPartitionName,PartitionInfo *pPartitionInfo)
{
FILE *fp = NULL;
char str[128] = {0};
char *p = NULL,*q = NULL,*pTmpStr = NULL;
int i = 0;
fp = fopen(MOUNTS_INFO, "r");
if (fp < 0)
{
printf("open %s failed\n",MOUNTS_INFO);
return -1;
}
while (NULL != fgets(str,sizeof(str),fp))
{
p = strstr(str,pPartitionName);
if (NULL != p)
{
for(i = 0;i < 4; i++)
{
if (0 == i)
{
q = strtok_r(str," ",&pTmpStr);
strcpy(pPartitionInfo->devName,q);
}
if (1 == i)
{
q = strtok_r(p," ",&pTmpStr);
strcpy(pPartitionInfo->dirName,q);
}
if (2 == i)
{
q = strtok_r(p," ",&pTmpStr);
strcpy(pPartitionInfo->fsType,q);
}
if (3 == i)
{
q = strtok_r(p,",",&pTmpStr);
strcpy(pPartitionInfo->authority,q);
}
p = pTmpStr;
}
}
}
fclose(fp);
return 0;
}
int main()
{
int status = -1;
PartitionInfo partitionInfo;
memset(&partitionInfo,0,sizeof(PartitionInfo));
status = getPartitionInfo("/dev/pts",&partitionInfo);
if(status < 0)
{
printf("get partition info failed\n");
return -1;
}
printf("devName:%s\n",partitionInfo.devName);
printf("dirName:%s\n",partitionInfo.dirName);
printf("fsType:%s\n",partitionInfo.fsType);
printf("authority:%s\n",partitionInfo.authority);
return 0;
}
运行结果
root@firefly:~/mnt# ./get_fsType
devName:devpts
dirName:/dev/pts
fsType:devpts
authority:rw