zoukankan      html  css  js  c++  java
  • 修改环境变量

    Linux下有两个函数用来查询和设置环境变量

    char *getenv(const char *name);

    int putenv(const char *string);

    getenv用于查询指定的环境变量的值,成功则返回该值,否则返回null。

    putenv以一个键值对的格式设置给定的环境变量的值

     1 #include <stdlib.h>
     2 #include <stdio.h>
     3 #include <string.h>
     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]
    ");
    12         exit(-1);
    13     }
    14 
    15     var = argv[1];
    16     value = getenv(var);
    17     if(value)
    18     {
    19         printf("Variable %s has value %s
    ", var, value);
    20     }
    21     else
    22     {
    23         printf("Variable %s has no value
    ");
    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
    ");
    34             exit(1);
    35         }
    36         strcpy(string, var);
    37         strcat(string, "=");
    38         strcat(string, value);
    39         printf("calling putenv with: %s
    ", string);
    40         if(putenv(string) != 0)
    41         {
    42             fprintf(stderr, "putenv failed
    ");
    43             free(string);
    44             exit(1);
    45         }
    46         
    47         value = getenv(var);
    48         if(value)
    49         {
    50             printf("New value of %s is %s
    ", var, value);
    51         }
    52         else
    53         {
    54             printf("New value of %s is null??
    ", var);
    55         }
    56         
    57         return 0;
    58     }
    59 }
  • 相关阅读:
    Linux 添加Nginx 到 service 启动
    PHP编译安装时常见错误解决办法,php编译常见错误
    7 适配器模式
    6 单例模式及其多线程问题
    5 简单工厂、工厂、抽象工厂
    4 装饰者模式
    3 观察者模式
    2 策略模式
    1 UML基础
    代码操作Word时,目录自动更新的两种方法
  • 原文地址:https://www.cnblogs.com/lit10050528/p/3981491.html
Copyright © 2011-2022 走看看