修改環境變數

來源:互聯網
上載者:User

標籤:style   blog   color   io   ar   div   sp   log   on   

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]\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 }

 

修改環境變數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.