xref: /original-bsd/lib/libc/stdlib/getenv.c (revision c3e32dec)
1 /*
2  * Copyright (c) 1987, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)getenv.c	8.1 (Berkeley) 06/04/93";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <stdlib.h>
13 #include <stddef.h>
14 #include <string.h>
15 
16 char *__findenv __P((const char *, int *));
17 
18 /*
19  * getenv --
20  *	Returns ptr to value associated with name, if any, else NULL.
21  */
22 char *
23 getenv(name)
24 	const char *name;
25 {
26 	int offset;
27 
28 	return (__findenv(name, &offset));
29 }
30 
31 /*
32  * __findenv --
33  *	Returns pointer to value associated with name, if any, else NULL.
34  *	Sets offset to be the offset of the name/value combination in the
35  *	environmental array, for use by setenv(3) and unsetenv(3).
36  *	Explicitly removes '=' in argument name.
37  *
38  *	This routine *should* be a static; don't use it.
39  */
40 char *
41 __findenv(name, offset)
42 	register const char *name;
43 	int *offset;
44 {
45 	extern char **environ;
46 	register int len;
47 	register const char *np;
48 	register char **p, *c;
49 
50 	if (name == NULL || environ == NULL)
51 		return (NULL);
52 	for (np = name; *np && *np != '='; ++np)
53 		continue;
54 	len = np - name;
55 	for (p = environ; (c = *p) != NULL; ++p)
56 		if (strncmp(c, name, len) == 0 && c[len] == '=') {
57 			*offset = p - environ;
58 			return (c + len + 1);
59 		}
60 	return (NULL);
61 }
62