Linux操作环境变量 getenv函数、setenv函数、unsetenv函数使用

1、getenv函数

获取环境变量的值

man 3 getenv
 
    #include<stdlib.h>
    char *getenv(const char*name);
    DESCRIPTION
       The getenv() function  searches the  environment list to find theenvironment variable name, and returns a pointer to the corresponding valuestring.


成功返回环境变量的值,失败返回NULL

 

 

2、setenv函数unsetenv函数

命令查看: man 3 setenv


NAME
       setenv - change or add an environmentvariable      //改变或添加一个环境变量
SYNOPSIS
       #include <stdlib.h>
       int setenv(const char *name, const char*value, int overwrite);
           int unsetenv(const char *name);

overwrite参数:
    非0表示覆盖原有环境变量,0表示不覆盖。
返回值:
       The setenv() function returns zero onsuccess, or -1 on error, with errno set to indicate the  cause of the error.
   The unsetenv()  function  returns zero  on success, or -1 on error,with errno set to indicate the cause of the error.


可见,两个函数都是成功返回0,失败返回-1,并记录errno信息。

 

测试程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(void)
{
    char* val;
    const char* name ="ABC";
    
    //获取ABC环境变量的值
    val = getenv(name);
    printf("No.1  %s=%s\n", name, val);
 
    //覆盖写入环境变量
    setenv(name, "I amsure of that I will get it", 1);
    printf("No.2%s=%s\n", name, val);
    
    val = getenv(name);
    printf("No.3%s=%s\n", name, val);
    
    //删除一个环境变量
    int ret =unsetenv("ABC");
    printf("ret =%d\n",ret);
    
    val = getenv(name);
    printf("No.3 %s=%s\n",name, val);
     
    return 0;
}
 


编译执行:

yu@ubuntu:~/cplusplus/hjbl_环境变量$ gcc env_opt.c -o env_opt
yu@ubuntu:~/cplusplus/hjbl_环境变量$ ./env_opt 
No.1 ABC=(null)
No.2 ABC=(null)
No.3 ABC=I am sure of that I will get it
ret = 0
No.3 ABC=(null)



  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值