Modify getfullname so it performs the same processing that
[mmh] / test / getfullname.c
1 /*
2  * getfullname.c - Extract a user's name out of the GECOS field in
3  *                 the password file.
4  *
5  * This code is Copyright (c) 2012, by the authors of nmh.  See the
6  * COPYRIGHT file in the root directory of the nmh distribution for
7  * complete copyright information.
8  */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <sys/types.h>
15 #include <pwd.h>
16
17 int
18 main(int argc, char *argv[])
19 {
20         struct passwd *pwd;
21         char name[BUFSIZ], *p;
22
23         if (argc > 1) {
24                 fprintf (stderr, "usage: %s\n", argv[0]);
25         }
26
27         pwd = getpwuid(getuid());
28
29         if (! pwd) {
30                 fprintf(stderr, "Unable to retrieve user info for "
31                         "userid %d\n", getuid());
32                 exit(1);
33         }
34
35         /*
36          * Perform the same processing that getuserinfo() does.
37          */
38
39         strncpy(name, pwd->pw_gecos, sizeof(name));
40
41         name[sizeof(name) - 1] = '\0';
42
43         /*
44          * Stop at the first comma
45          */
46
47         if ((p = strchr(name, ',')))
48                 *p = '\0';
49
50         /*
51          * Quote the entire string if it has a "." in it
52          */
53
54         if (strchr(name, '.')) {
55                 char tmp[BUFSIZ];
56
57                 snprintf(tmp, sizeof(tmp), "\"%s\"", name);
58                 strncpy(name, tmp, sizeof(name));
59
60                 name[sizeof(name) - 2] = '"';
61                 name[sizeof(name) - 1] = '\0';
62         }
63
64         printf("%s\n", name);
65
66         exit(0);
67 }