-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsetenv.c
52 lines (42 loc) · 1.13 KB
/
setenv.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
//+doc put a string into the environmental vars
// UNTESTED (!) TODO
// the supplied string's pointer is put into the environmental array of pointers.
// The supplied strings are copied into memory.
// If overwrite is zero, an existing environmental variable is not overritten.
// If overwrite is 1, the environmental variable is overwritten,
// but not(!) freed from memory.
// The supplied value is not checked for e.g. an '='
//
// Returns:
// - 0 on success
// - EINVAL on error
//+depends environ getenv strncmp ret_errno malloc strcpy strlen stpcpy
//+def
int setenv( const char *name, const char *value, int overwrite ){
char **envp;
int len = strlen(name);
for ( envp=environ; *envp; envp++ ) {
if ( strncmp((char*)*envp, (char*)name, len) == 0 ) {
if ( overwrite == 0 )
return(0);
*envp=malloc(len+1+strlen(value));
if ( !*envp )
ret_errno(ENOMEM);
char *c = stpcpy(*envp,name);
*c = '=';
c++;
strcpy(c,value);
return(0);
}
}
*envp=malloc(len+1+strlen(value));
if ( !*envp )
ret_errno(ENOMEM);
char *c = stpcpy(*envp,name);
*c = '=';
c++;
strcpy(c,value);
envp++;
*envp=0;
return(0);
}