• 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 ",strerror(errno));  
    12.    while ((m = getmntent(f)))        //read next line  
    13.      printf("Drive %s, name %s,type  %s,opt  %s ", 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指向的文件追加最后一行数据。

  • 相关阅读:
    Maven版本管理
    ArrayList集合实现RandomAccess接口有何作用?为何LinkedList集合却没实现这接口
    java常用集合框架关系
    重写equals和hashCode
    项目的继承和聚合详解
    Installation Manager1.8安装
    关于java按位操作运算
    正数负数的二进制表示
    springboot问题排解
    int和Integer有什么区别
  • 原文地址:https://www.cnblogs.com/zhouhbing/p/4284566.html
Copyright © 2020-2023  润新知