linux中getmntent setmntent endmntent 用法例子

來源:互聯網
上載者:User

標籤:

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指向的檔案追加最後一行資料。

linux中getmntent setmntent endmntent 用法例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.