C获取linux系统环境变量方法(Environment Variables)

主要有三种方法,都很简单。


一个单纯c语言获取的方式

<span style="font-family:Microsoft YaHei;font-size:14px;">#include <stdio.h>
#include <stdlib.h>

int main(){
	char *pathvar = getenv("PATH"); 
	printf("pathvar is : %s\n",pathvar);
	return 0;
}
</span>

getenv() 是在stdlib中定义的,当然我们也可以在c++中,通过 #include<cstdlib> std:getenv()来使用它.若考虑可移植性,这两种方式都是可以优先使用的


 envp

#include <stdio.h>

int main(int argc,char **argv,char **envp){
	printf("the 1st envp is : %s\n",envp[0]);
	return 0;
}

注:这里需要注明的是,关于envp,如果考虑程序的可移植性的话,最好不要用envp用为main函数的第三个参数.

因为他是一种常见的unix系列系统的扩展. envp 是一个以null结尾的字符串数组,在MicrosoftC++中可以使用.如果你用的是wmain.可以你 wchar_t 代替char来标识它.

虽然是一种常见的扩展,但并不是所有的系统中都有这种扩展,所以在考虑程序的可移植性的时候最好不要使用他.

因为在 C99 Standard 中只有两种合法的Cmian函数定义

a) int main(void)

and

b) int main(int argc, char **argv) or equivalent

and it allows implementations to define other formats (which can allow a 3rd argument)

c) or in some other implementation-defined manner.

extern char **environ

#include <stdio.h>

extern char **environ;

int main(int argc,char **argv){
	printf("get envp by environ,the 2nd envp is : %s\n",++*environ);
	return 0;	
}<span style="color:#ff0000;">
</span>

这里同样需要说明的是,extern char **environ.在Posix中是在<unistd.h>中声明的.详细信息可以参看:http://www.unix.org/single_unix_specification/  它也是unixsm的,并且在windows中是没有定义的,所以但是在实践中,考虑最好还是使用getenv()函数来取得相关的环境变量.


参考文章:http://www.cnblogs.com/algorithmic/archive/2012/09/23/2698604.html






  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值