21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

210 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>user database, and the I/O to scan it, are only incurred if the user’s main program actuallycalls one of these functions. If this library file is loaded along with a user’s program, but noneof the routines are ever called, then there is no extra runtime overhead. (The alternativeis move the body of _pw_init into a BEGIN rule, which always runs pwcat. This simplifiesthe code but runs an extra process that may never be needed.)In turn, calling _pw_init is not too expensive, because the _pw_inited variable keepsthe program from reading the data more than once. If you are worried about squeezingevery last cycle out of your awk program, the check of _pw_inited could be moved out of_pw_init and duplicated in all the other functions. In practice, this is not necessary, sincemost awk programs are I/O-bound, and it clutters up the code.The id program in Section 13.2.3 [Printing out User Information], page 224, uses thesefunctions.12.6 Reading the Group DatabaseMuch of the discussion presented in Section 12.5 [Reading the User Database], page 206,applies to the group database as well. Although there has traditionally been a well-knownfile (‘/etc/group’) in a well-known format, the POSIX standard only provides a set of Clibrary routines ( and getgrent) for accessing the information. Even though thisfile may exist, it likely does not have complete information. Therefore, as with the userdatabase, it is necessary to have a small C program that generates the group database asits output.grcat, a C program that “cats” the group database, is as follows:/** grcat.c** Generate a printable version of the group database*/#include #include intmain(argc, argv)int argc;char **argv;{struct group *g;int i;while ((g = getgrent()) != NULL) {printf("%s:%s:%ld:", g->gr_name, g->gr_passwd,(long) g->gr_gid);for (i = 0; g->gr_mem[i] != NULL; i++) {printf("%s", g->gr_mem[i]);if (g->gr_mem[i+1] != NULL)putchar(’,’);}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!