[code小心得]mount table , /etc/passwd , /etc/group

Hi   大家好

這次紀錄一下  小 Code.


#include <"stdio.h"> #include <"errno.h"> #include <"mntent.h"> /* for setmntent()*/ #include <"unistd.h"> /* for getopt() */ int main(void) { FILE *mountTable = NULL; struct mntent* mnt = NULL; /* Using mount point to read /etc/mtab file */ if ((mountTable = setmntent("/etc/mtab", "r")) == NULL ) { printf("Open fail\n"); //return FAIL; } while((mnt=getmntent(mountTable))) { printf("mnt_fsname =%s\n", mnt->mnt_fsname); printf("mnt_dir =%s\n", mnt->mnt_dir); printf("mnt_type =%s\n", mnt->mnt_type); printf("mnt_opts =%s\n", mnt->mnt_opts); } endmntent(mountTable); return 0; } #include <"stdio.h"> #include <"pwd.h"> int main(void) { struct passwd *username; while( ( username=getpwent() ) != 0 ) { printf("User_name: %s UID: %ld\n", username->pw_name, (long)username->pw_uid); } endpwent(); return 0; } #include <"stdio.h"> #include <"grp.h"> int main(void) { struct group *groupname; while( ( groupname=getgrent() ) != 0 ) { printf("Group_name: %s GID: %d\n", groupname->gr_name, groupname->gr_gid); } endgrent(); return 0; }
以上 這幾個 利用 Linux C 的特性,在head file 增加 專屬的宣告,就有現成的API 和struct 可供運用。 第一個 針對mount table 二跟三 就是針對 讀取/etc/passwd /etc/group的 檔案

細節部份 就請在去man一下  或是google爬文囉。

http://linux.die.net/man/3/getmntent
http://man7.org/linux/man-pages/man3/getpwent.3.html
http://man7.org/linux/man-pages/man3/getgrent.3.html

如果要自己parser 可能會有些痛苦.....

以上 下台一鞠躬

留言