home *** CD-ROM | disk | FTP | other *** search
- #include <stdio.h>
- #include <pwd.h>
-
- static char *pwdfile = "/etc/passwd"; /* default passwd file */
- static FILE *fp = NULL;
- static struct passwd curentry; /* static data to return */
-
- void setpwfile (cp)
- char *cp;
- {
- pwdfile = cp;
- }
-
- int setpwent ()
- {
- if (fp)
- rewind (fp);
- else if ((fp = fopen (pwdfile, "r")) == NULL)
- {
- #ifdef VERBOSE
- fprintf (stderr,
- "setpwent: %s non-existant or unreadable.\n", pwdfile);
- #endif
- return (0);
- }
- return (1);
- }
-
- int endpwent ()
- {
- if (fp)
- {
- fclose (fp);
- fp = NULL;
- }
- return 1;
- }
-
- struct passwd *getpwent ()
- {
- if (! fp && ! setpwent ())
- return (NULL);
-
- if (! nextent ())
- return (NULL);
- else
- return (& curentry);
- }
-
- struct passwd *getpwuid (uid)
- register int uid;
- {
- if (! setpwent ())
- return (NULL);
-
- while (nextent ())
- if (curentry.pw_uid == uid)
- return (& curentry);
-
- return (NULL);
- }
-
- struct passwd *getpwnam (name)
- register char *name;
- {
- if (! setpwent ())
- return (NULL);
-
- while (nextent ())
- if (strcmp (curentry.pw_name, name) == 0)
- return (& curentry);
-
- return (NULL);
- }
-
- static char savbuf[BUFSIZ];
-
- static int nextent ()
- {
- register char *cp;
-
- if (! fp && ! setpwent ())
- return (0);
-
- while (fgets (savbuf, sizeof(savbuf), fp) != NULL)
- {
- for (cp = savbuf; *cp && *cp != ':'; cp++)
- ;
- curentry.pw_name = savbuf;
- *cp++ = '\0';
- curentry.pw_passwd = cp;
- for (; *cp && *cp != ':'; cp++)
- ;
- *cp++ = '\0';
- curentry.pw_uid = atoi (cp);
- for (; *cp && *cp != ':'; cp++)
- ;
- *cp++ = '\0';
- curentry.pw_gid = atoi (cp);
- for (; *cp && *cp != ':'; cp++)
- ;
- *cp++ = '\0';
- curentry.pw_gecos = cp;
- for (; *cp && *cp != ':'; cp++)
- ;
- *cp++ = '\0';
- curentry.pw_dir = cp;
- for (; *cp && *cp != ':'; cp++)
- ;
- *cp++ = '\0';
- curentry.pw_shell = cp;
- for (; *cp && *cp != ':' && *cp != '\n'; cp++)
- ;
- *cp++ = '\0';
- return (1);
- }
- return (0);
- }
-
- #ifdef TEST
- main (argc, argv)
- int argc;
- char **argv;
- {
- struct passwd *pwd;
-
- if (argc > 1)
- setpwfile (argv[1]);
-
- setpwent ();
- while ((pwd = getpwent ()) != NULL)
- {
- printf ("%s:\n\t%s\n\t%d\n\t%d\n\t%s\n\t%s\n\t%s\n",
- pwd->pw_name,
- pwd->pw_passwd,
- pwd->pw_uid,
- pwd->pw_gid,
- pwd->pw_gecos,
- pwd->pw_dir,
- pwd->pw_shell);
- }
- endpwent ();
-
- if (pwd = getpwnam ("operator"))
- printf ("%s:\n\t%s\n\t%d\n\t%d\n\t%s\n\t%s\n\t%s\n",
- pwd->pw_name,
- pwd->pw_passwd,
- pwd->pw_uid,
- pwd->pw_gid,
- pwd->pw_gecos,
- pwd->pw_dir,
- pwd->pw_shell);
-
- if (pwd = getpwuid (1))
- printf ("%s:\n\t%s\n\t%d\n\t%d\n\t%s\n\t%s\n\t%s\n",
- pwd->pw_name,
- pwd->pw_passwd,
- pwd->pw_uid,
- pwd->pw_gid,
- pwd->pw_gecos,
- pwd->pw_dir,
- pwd->pw_shell);
- }
- #endif
-