-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgetenv.c
More file actions
57 lines (53 loc) · 1.2 KB
/
getenv.c
File metadata and controls
57 lines (53 loc) · 1.2 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
const char *envstr; // represents the latest return value of getenv()
char *tmpvar; // saved TMP string
char *tempvar; // saved TEMP string
// get and store "TMP"'s value, with robust error checking
envstr = getenv("TMP");
if (!envstr) {
puts("getenv failed: no match found");
return -1;
}
tmpvar = strdup(envstr);
if (!tmpvar) {
puts("strdup failed.");
return -1;
}
printf("TMP = %s\n", tmpvar);
// get and store "TEMP"'s value, with robust error checking
envstr = getenv("TEMP");
if (!envstr) {
puts("getenv failed: no match found");
free(tmpvar);
tempvar = NULL;
return -1;
}
tempvar = strdup(envstr);
if (!tempvar) {
puts("strdup failed.");
free(tmpvar);
tmpvar = NULL;
return -1;
}
printf("TEMP = %s\n", tempvar);
if (strcmp(tmpvar, tempvar) == 0) {
if (puts("TMP and TEMP are the same.\n") == EOF) {
/* Handle error */
puts("puts error");
}
}
else {
if (puts("TMP and TEMP are NOT the same.\n") == EOF) {
/* Handle error */
puts("puts error");
}
}
free(tempvar); // caller is responsible for freeing memory allocated by strdup
tempvar = NULL;
free(tmpvar);
tmpvar = NULL;
}