The mntent structure is defined in <mntent.h>, as follows: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 */
};
The structure can correspond to the data of each row in/etc/mtab or/etc/fstab, if the program needs to access/etc/mtab or/etc/fstab files, then the function getmntent with Linux comes directly to the data of a row, Very convenient. Setmntent can create an FD based on the file and open type specified by the parameter, and the FD can pass in the Getmntent function to get a row of data into the mntent structure, as in the following example:
[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;
- }
It is important to note that getmntent is not reentrant function, if a program in a number of places at the same time call getmntent, may not get the desired results, then you can use the Getmntent_r function instead, the prototype is as follows:
struct Mntent *getmntent_r (FILE *fp, struct mntent *mntbuf, char *buf, int buflen);
Getmntent_r will store the data in the user-supplied memory (MNTBUF), rather than being managed by the system.
Addmntent (file *fp, const struct mntent *mnt) can append the last row of data to the file that the FP points to.
Examples of getmntent setmntent endmntent usage in Linux