linux中getmntent setmntent endmntent 用法例子

mntent 结构是在 <mntent.h> 中定义,如下:

              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 */

              };

该结构可以对应/etc/mtab或者/etc/fstab中的每一行的数据,如果是程序有需求要访问/etc/mtab或者/etc/fstab文件,那么使用linux自带的函数getmntent就可以直接获取一行的数据,很方便。setmntent可以根据参数指定的文件及打开类型来创建一个FD,该FD可以传入getmntent函数来获取一行的数据存入mntent结构中,例子如下:

 

[cpp] view plaincopy
 
  1. #include <mntent.h>  
  2. #include <stdio.h>  
  3. #include <errno.h>  
  4. #include <string.h>  
  5. int main()  
  6. {  
  7.    struct mntent *m;  
  8.    FILE *f = NULL;  
  9.    f = setmntent("/etc/fstab","r"); //open file for describing the mounted filesystems  
  10.    if(!f)  
  11.        printf("error:%s\n",strerror(errno));  
  12.    while ((m = getmntent(f)))        //read next line  
  13.      printf("Drive %s, name %s,type  %s,opt  %s\n", m->mnt_dir, m->mnt_fsname,m->mnt_type,m->mnt_opts );  
  14.    endmntent(f);   //close file for describing the mounted filesystems  
  15.    return 0;  
  16. }  

值得注意的是getmntent是不可重入函数,如果一个程序中多个地方同时调用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指向的文件追加最后一行数据。

posted @ 2015-02-10 18:25  周人假的  阅读(3625)  评论(0编辑  收藏  举报