-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtildepath.c
140 lines (115 loc) · 2.39 KB
/
tildepath.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
T* NAME
*
* tildepath.c - Convert ~name to a path.
*
T* SYNOPSIS
*
* char *tildepath(path);
* char *path; - ~path specification
*
T* DESCRIPTION
*
* This routine takes a path of the for ~[name]/... and returns the true
* path for the users home directory. Any additional path information is
* tacked onto the end of the new path.
*
T* RETURNS
*
* A path if one is valid, NULL otherwise. Note that the memory allocated
* for the new path should be freed by the calling program.
*
T* AUTHOR
*
* Stephen Martin, March 12, 1991.
*/
/*
* Version
*/
/* static char SccsId[] = { "@(#) tildepath.c 1.1@(#)" }; */
/*
* Include Files
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pwd.h>
#include <malloc.h>
#include <string.h>
/*
* Define Statements
*/
#ifndef NULL
#define NULL (char *) 0
#endif
/*
* tildepath()
*/
char *
tildepath(path)
char *path; /* Path starting with ~ */
{
/*
* Local Variables
*/
char *username; /* Points to the username */
char *rest; /* Rest of input path */
char *result; /* Used to construct the result */
struct passwd *pwent; /* Password entry for user */
int size; /* Length of new path */
/*
* Functions
*/
/* char *strdup(); */ /* Make a copy of a path */
/*
* If the path doesn't start with ~ quit right now
*/
if (path[0] != '~')
return(NULL);
/*
* Find the name delimited by / or the end of the string
*/
if ((username = strdup(++path)) == NULL)
return(NULL);
if ((rest = strchr(username, '/'))) {
*rest = '\0';
rest++;
}
/*
* Get the user's password entry
*/
if (username[0])
pwent = getpwnam(username);
else
pwent = getpwuid(getuid());
/*
* Check to see if a password entry was found
*/
if (pwent == NULL) {
free(username);
return(NULL);
}
/*
* Determine the size of the new path and allocate space for it
*/
size = strlen(pwent->pw_dir) + 1;
if (rest && (rest[0] != '\0'))
size += strlen(rest) + 1;
if ((result = calloc(size, sizeof(char))) == NULL) {
free(username);
return(NULL);
}
/*
* Copy over the new path
*/
strcpy(result, pwent->pw_dir);
if (rest && (rest[0] != '\0')) {
strcat(result, "/");
strcat(result, rest);
}
/*
* Done
*/
free(username);
return(result);
}