標籤:
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
- #include <mntent.h>
- #include <stdio.h>
- #include <errno.h>
- #include <string.h>
- int main()
- {
- struct mntent *m;
- FILE *f = NULL;
- 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,可能會得不到想要的結果,那麼可以用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 用法例子