将getenv函数-->_dupenv_s函数

C语言中getenv()读取环境变量的当前值的函数


_dupenv_s is a Microsoft function, designed as a more secure form of getenv.

_dupenv_s allocates the buffer itself; you have to pass it a pointer to a pointer and it sets this to the address of the newly allocated buffer.

For example,

char* buf = nullptr;
size_t sz = 0;
if (_dupenv_s(&buf, &sz, "EnvVarName") == 0 && buf != nullptr)
{
    printf("EnvVarName = %s\n", buf);
    free(buf);
}

Note that you're responsible for freeing the returned buffer.

原形:char *getenv(const char *name)

功能:返回一给定的环境变量值,环境变量名可大写或小写。如果指定的变量在环境中未定义,则返回一空串。
用法:
   #include <stdlib.h>
   char *s;
   s=getenv("TMP_DIR");
 
但是,在VS2005编译的时候,会出现如下警告:warning C4996: 'getenv': This function or variable may be unsafe. Consider using _dupenv_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
 
_dupenv_s原形:
errno_t _dupenv_s(
   char **buffer,
   size_t *numberOfElements,
   const char *varname
);
参数说明:
buffer:Buffer to store the variable's value.
numberOfElements:Size of buffer.
varname:Environment variable name. 
因此,如果用_dupenv_s来实现的话,如下:
char *s;
size_t len;
errno_t err = _dupenv_s( &s, &len, env );
if ( err ) exit(-1);
free(tmp);
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值