C语言中getenv()读取环境变量的当前值的函数
用法:
#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);
_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);