forked from efrengaribaldi/Linux-and-UNIX-System-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathugid_functions.c
63 lines (50 loc) · 1.45 KB
/
ugid_functions.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* Listing 8-1: Functions to convert user and group IDs to and from user
and group names */
#include <pwd.h>
#include <grp.h>
#include <ctype.h>
#include <stdlib.h>
/* This is an integer data type used to represent user IDs.
In the GNU C Library, this is an alias for unsigned int */
char* userNameFromId(__uid_t uid) {
struct passwd *pwd;
pwd = getpwuid(uid);
return (pwd == NULL) ? NULL : pwd->pw_name;
}
__uid_t userIdFromName(const char *name) {
struct passwd *pwd;
__uid_t u;
char *endptr;
if (name == NULL || *name == '\0')
return -1;
/* converts the initial part of the string in str to a long int value
according to the given base. */
u = strtol(name, &endptr, 10);
if (*endptr == '\0')
return u;
pwd = getpwnam(name);
if (pwd == NULL)
return -1;
return pwd->pw_uid;
}
char* groupNameFromId(__gid_t gid) {
struct group *grp;
grp = getgrgid(gid);
return (grp == NULL) ? NULL : grp->gr_name;
}
/* This is an integer data type used to represent group IDs.
In the GNU C Library, this is an alias for unsigned int. */
__gid_t groupIdFromName(const char *name) {
struct group *grp;
__gid_t g;
char *endptr;
if (name == NULL || *name == '\0')
return -1;
g = strtol(name, &endptr, 10);
if (*endptr == '\0')
return g;
grp = getgrnam(name);
if (grp == NULL)
return -1;
return grp->gr_gid;
}