linux中使用getmntent setmntent endmntent 用法
1.首先需要知道mntent这个结构体,它是专门用来对应/etc/mtab或/etc/fstab 和 /proc/mounts中的每一行的数据。
mntent定义如下:
struct mntent {
char *mnt_fsname; /* name of mounted file system */
char *mnt_dir; /* file system path prefix */
char *mnt_type; /* mount type (see mntent.h) */
char *mnt_opts; /* mount options (see mntent.h) */
int mnt_freq; /* dump frequency in days */
int mnt_passno; /* pass number on parallel fsck */
};
char *mnt_fsname; /* 挂载的文件系统的名字 */
char *mnt_dir; /* 挂载点 */
char *mnt_type; /* 文件系统类型:ufs、nfs 等 */
char *mnt_opts; /* 选项,以逗号为分隔符 */
int mnt_freq; /* Dump 的频率(以天为单位) */
int mnt_passno; /* fsck检查的次序 */
};
2.使用linux自带的getmntent可以获取一行数据,一般配合while循环来将整个文件中每一行的信息传递给结构体。
setmntent是用来打开指定文件及文件类型来创建一个FILE,该FILE可以传入到getmnment函数来获取一行数据存入到mnment中结构中。
#include <mntent.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
struct mntent *m;
FILE *f = NULL; //file pointer
f = setmntent("/etc/fstab","r"); //open file for describing the mounted filesystems
if(!f)
printf("error:%s\n",strerror(errno));
while ((m = getmntent(f))) //read next line
printf("Drive %s, name %s,type %s,opt %s\n", m->mnt_dir, m->mnt_fsname,m->mnt_type,m->mnt_opts );
endmntent(f); //close file for describing the mounted filesystems
return 0;
}
值得注意的是,getmntent不能在一个程序中多个地方同时调用,可能会得到不一样的结果,可以·按使用getmntent_r来替代。
struct mntent *getmntent_r(FILE *fp, struct mntent *mntbuf, char *buf, int buflen);
getmntent_r会把数据存放在用户提供的内存中(mntbuf),而不是由系统管理。
addmntent(FILE *fp, const struct mntent *mnt) 可以在fp指向的文件追加最后一行数据。