[Linux] Obtain file system mount information in the program

The Linux shell can obtain the current file system mount information by viewing the /etc/mtab or /proc/mounts file, for example:

Reading /etc/mtab or /proc/mounts in the program, parsing the string is cumbersome, you can use the convenient function provided by mntent:

FILE *setmntent(const char *filename, const char *type);
struct mntent *getmntent(FILE *filep);
int endmntent(FILE *filep);



(1) setmntent is used to open /etc/mtab or a table file in the same format. Read open)
returns a FILE pointer (for mntent operation) when successful, and returns NULL when it fails
 
(2) getmntent is used to read each line of the file, parse the parameters of each line into the mntent structure, and the storage space of the mntent structure is statically allocated (free is not required), the value of the structure will be overwritten in the next getmntent

mntent structure definition:

struct mntent
{
char *mnt_fsname;  
char *mnt_dir;     
char *mnt_type;    
char *mnt_opts;    
int mnt_freq;      
int mnt_passno;    
};


The parameter filep is the FILE pointer returned by setmntent.
It returns the pointer to mntent when it succeeds, and returns NULL when it fails.
 
(3) endmntent is used to close the opened table file and always returns 1

Sample program:

#include
#include
#include
#include

int main(void)
{
char *filename ="/proc/mounts";
FILE *mntfile; 
struct mntent *mntent;
  
mntfile = setmntent(filename,"r");
if (!mntfile) {
printf("Failed to read mtab file, error [%s]\n",
strerror(errno));
return -1;

while(mntent = getmntent(mntfile))
printf("%s, %s, %s, %s\n",
mntent->mnt_dir,
mntent->mnt_fsname,
mntent->mnt_type,
mntent->mnt_opts);
 
endmntent(mntfile);
return 0;

Guess you like

Origin blog.csdn.net/Vincent20111024/article/details/131005616