Linux下有两个函数用来查询和设置环境变量
char *getenv(const char *name);
int putenv(const char *string);
getenv用于查询指定的环境变量的值,成功则返回该值,否则返回null。
putenv以一个键值对的格式设置给定的环境变量的值
1 #include2 #include 3 #include 4 5 int main(int argc, char **argv) 6 { 7 char *var, *value; 8 9 if(argc == 1 || argc > 3)10 {11 fprintf(stderr, "usage:environ var [value]\n");12 exit(-1);13 }14 15 var = argv[1];16 value = getenv(var);17 if(value)18 {19 printf("Variable %s has value %s\n", var, value);20 }21 else22 {23 printf("Variable %s has no value\n");24 }25 26 if(argc == 3)27 {28 char *string;29 value = argv[2];30 string = malloc(strlen(var) + strlen(value) + 2);31 if(!string)32 {33 fprintf(stderr, "out of memory\n");34 exit(1);35 }36 strcpy(string, var);37 strcat(string, "=");38 strcat(string, value);39 printf("calling putenv with: %s\n", string);40 if(putenv(string) != 0)41 {42 fprintf(stderr, "putenv failed\n");43 free(string);44 exit(1);45 }46 47 value = getenv(var);48 if(value)49 {50 printf("New value of %s is %s\n", var, value);51 }52 else53 {54 printf("New value of %s is null??\n", var);55 }56 57 return 0;58 }59 }