#include <stdlib.h>
char *getenv(const char *name);
int putenv(const char *string);
01 #include <stdlib.h>
02 #include <stdio.h>
03 #include <string.h>
04
05 int main(int argc, char *argv[])
06 {
07 char *var, *value;
08
09 if(argc == 1 || argc > 3) {
10 fprintf(stderr, "usage: environ var [value]\n");
11 exit(1);
12 }
13
14 var = argv[1];
15 value = getenv(var);
16
17 if(value)
18 printf("Variable %s has value %s\n", var, value);
19 else
20 printf("Variable %s has no value\n", var);
21
22 if(argc == 3) {
23 char *string;
24 value = argv[2];
25 string = malloc(strlen(var) + strlen(value)+2);
26 if(!string) {
27 fprintf(stderr, "out of memory\n");
28 exit(1);
29 }
30
31 strcpy(string,var);
32 strcat(string,"=");
33 strcat(string,value);
35
36 if(putenv(string) != 0) {
37 fprintf(stderr,"putenv failed\n");
38 free(string);
39 exit(1);
40 }
41
42 value = getenv(var);
43 if(value)
44 printf("New value of %s is %s\n", var, value);
45 else
46 printf("New value of %s is null??\n", var);
47 }
48
49 exit(0);
50 }
[root@localhost C]# ./environ.exe HOME #得到当前的 HOME 变量值
Variable HOME has value /root
[root@localhost C]# ./environ.exe FRED hello #对 FRED 进行赋值(hello)
Variable FRED has no value
New value of FRED is hello
[root@localhost C]# ./environ.exe FRED #当前进程结束了,这个值也随之消失
Variable FRED has no value
[beyes@SLinux C]$ export SELDEF=just_for_testing
[beyes@SLinux C]$ echo $SELDEF
just_for_testing
#include <stdlib.h>
#include <stdio.h>
int main()
{
printf ("%s\n", getenv("SELDEF"));
return 0;
}
[beyes@SLinux C]$ ./getenv
just_for_testing
#include <stdio.h>
#include <stdlib.h>
int main()
{
if (putenv("SELDEF=set_by_putenv_function") != 0) {
perror ("putenv");
exit (EXIT_FAILURE);
}
printf ("%s\n", getenv("SELDEF"));
return (0);
}
[beyes@SLinux C]$ ./putenv
set_by_putenv_function
[beyes@SLinux C]$ echo $SELDEF
just_for_testing
欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) | Powered by Discuz! X3.2 |