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 }
  • 相关阅读:
    两种常用的jquery事件加载的方法 的区别
    .net修炼笔记
    C#获取MySql 数据常用的代码
    sql时间格式化
    UMEditor(Ueditor mini)修改图片上传路径
    LeetCode_101. Symmetric Tree
    LeetCode_100. Same Tree
    LeetCode_88. Merge Sorted Array
    LeetCode_83. Remove Duplicates from Sorted List
    LeetCode_70. Climbing Stairs
  • 原文地址:https://www.cnblogs.com/lit10050528/p/3981491.html
Copyright © 2011-2022 走看看