【Linux】程序内获取文件系统挂载信息

Linux shell可通过查看/etc/mtab或者/proc/mounts文件来获取当前文件系统挂载信息,示例:

程序内读取/etc/mtab或者/proc/mounts,解析字符串较为繁琐,可以使用mntent提供的方便函数:

FILE *setmntent(const char *filename, const char *type);
struct mntent *getmntent(FILE *filep);
int endmntent(FILE *filep);


(1)setmntent用来打开/etc/mtab或者同样格式的table文件
参数 filename为table文件的路径(例如/etc/mtab),参数type为打开文件的模式(与open类型,例如“r”为只读打开)
成功时,返回FILE指针(用于mntent操作),失败时返回NULL
 
(2)getmntent用来读取文件的每一行,解析每一行的参数到mntent结构,mntent结构的存储空间是静态分配的(不需要free),结构的值会在下一次getmntent时被覆盖

mntent结构定义:

struct mntent
{
char *mnt_fsname;  
char *mnt_dir;     
char *mnt_type;    
char *mnt_opts;    
int mnt_freq;      
int mnt_passno;    
};


参数filep是setmntent返回的FILE指针
成功时返回指向mntent的指针,错误时返回NULL
 
(3)endmntent用来关闭打开的table文件,总是返回1

示例程序:

#include
#include
#include
#include

int main(void)
{
char *filename ="/proc/mounts";
FILE *mntfile; 
struct mntent *mntent;
  
mntfile = setmntent(filename,"r");
if (!mntfile) {
printf("Failed to read mtab file, error [%s]\n",
strerror(errno));
return -1;

while(mntent = getmntent(mntfile))
printf("%s, %s, %s, %s\n",
mntent->mnt_dir,
mntent->mnt_fsname,
mntent->mnt_type,
mntent->mnt_opts);
 
endmntent(mntfile);
return 0;

猜你喜欢

转载自blog.csdn.net/Vincent20111024/article/details/131005616