getenv_s、_wgetenv_sgetenv_s, _wgetenv_s

从当前环境中获取值。Gets a value from the current environment. 这些版本的 getenv、_wgetenv 具有安全增强功能,如 CRT 中的安全功能所述。These versions of getenv, _wgetenv have security enhancements, as described in Security Features in the CRT.

重要

此 API 不能用于在 Windows 运行时中执行的应用程序。This API cannot be used in applications that execute in the Windows Runtime. 有关详细信息,请参阅通用 Windows 平台应用中不支持的 CRT 函数For more information, see CRT functions not supported in Universal Windows Platform apps.

语法Syntax

errno_t getenv_s(
   size_t *pReturnValue,
   char* buffer,
   size_t numberOfElements,
   const char *varname
);
errno_t _wgetenv_s(
   size_t *pReturnValue,
   wchar_t *buffer,
   size_t numberOfElements,
   const wchar_t *varname
);
template <size_t size>
errno_t getenv_s(
   size_t *pReturnValue,
   char (&buffer)[size],
   const char *varname
); // C++ only
template <size_t size>
errno_t _wgetenv_s(
   size_t *pReturnValue,
   wchar_t (&buffer)[size],
   const wchar_t *varname
); // C++ only

参数Parameters

pReturnValuepReturnValue
所需的缓冲区大小,如果找不到该变量,则为 0。The buffer size that's required, or 0 if the variable is not found.

bufferbuffer
用于存储环境变量值的缓冲区。Buffer to store the value of the environment variable.

numberOfElementsnumberOfElements
大小缓冲区Size of buffer.

varnamevarname
环境变量名称。Environment variable name.

返回值Return Value

如果成功,则为零;如果失败,则返回错误代码。Zero if successful; otherwise, an error code on failure.

错误条件Error Conditions

pReturnValuepReturnValue bufferbuffer numberOfElementsnumberOfElements varnamevarname 返回值Return Value
NULLNULL 任何any 任何any 任何any EINVALEINVAL
任何any NULLNULL >0>0 任何any EINVALEINVAL
任何any 任何any 任何any NULLNULL EINVALEINVAL

参数验证中所述,这些错误条件调用无效参数处理程序。Any of these error conditions invokes an invalid parameter handler, as described in Parameter Validation. 如果允许执行继续,则函数将设置errnoEINVAL并返回EINVALIf execution is allowed to continue, the functions set errno to EINVAL and return EINVAL.

此外,如果缓冲区太小,这些函数将返回ERANGEAlso, if the buffer is too small, these functions return ERANGE. 它们不会调用无效的参数处理程序。They do not invoke an invalid parameter handler. 写出所需的缓冲区大小以pReturnValue,从而使程序能够使用较大的缓冲区再次调用函数。They write out the required buffer size in pReturnValue, and thereby enable programs to call the function again with a larger buffer.

备注Remarks

Getenv_s函数将搜索的环境变量列表varnameThe getenv_s function searches the list of environment variables for varname. getenv_s不区分大小写,在 Windows 操作系统中。getenv_s is not case sensitive in the Windows operating system. getenv_s_putenv_s使用由全局变量指向该环境的副本 _environ来访问该环境。getenv_s and _putenv_s use the copy of the environment that's pointed to by the global variable _environ to access the environment. getenv_s操作仅在运行时库可以访问的数据结构上而不是在环境"段"是由操作系统创建相应的进程。getenv_s operates only on the data structures that are accessible to the run-time library and not on the environment "segment" that's created for the process by the operating system. 因此,程序使用envp参数主要wmain可能会检索无效信息。Therefore, programs that use the envp argument to main or wmain might retrieve invalid information.

_wgetenv_s是宽字符版本的getenv_s; 的自变量和返回值 _wgetenv_s是宽字符字符串。_wgetenv_s is a wide-character version of getenv_s; the argument and return value of _wgetenv_s are wide-character strings. _Wenviron全局变量是宽字符版本的 _environThe _wenviron global variable is a wide-character version of _environ.

在 MBCS 程序中 (例如,在 SBCS ASCII 程序中), _wenviron最初NULL因为环境多字节字符字符串组成。In an MBCS program (for example, in an SBCS ASCII program), _wenviron is initially NULL because the environment is composed of multibyte-character strings. 然后,在首次调用_wputenv,或在首次调用上 _wgetenv_s,如果 (MBCS) 环境已存在,创建,然后通过指向对应的宽字符字符串环境 _wenvironThen, on the first call to _wputenv, or on the first call to _wgetenv_s, if an (MBCS) environment already exists, a corresponding wide-character string environment is created and is then pointed to by _wenviron.

同样,在 Unicode (_wmain) 程序中, _environ最初NULL因为环境宽字符字符串组成。Similarly in a Unicode (_wmain) program, _environ is initially NULL because the environment is composed of wide-character strings. 然后,在首次调用_putenv,或在首次调用上getenv_s如果 (Unicode) 环境已存在,创建,然后由指向对应的 MBCS 环境 _environThen, on the first call to _putenv, or on the first call to getenv_s if a (Unicode) environment already exists, a corresponding MBCS environment is created and is then pointed to by _environ.

当程序中同时存在环境的两个副本(MBCS 和 Unicode)时,运行时系统必须保留这两个副本,而这将减慢执行时间。When two copies of the environment (MBCS and Unicode) exist simultaneously in a program, the run-time system must maintain both copies, and this causes slower execution time. 例如,当调用 _putenv,调用 _wputenv还自动执行,以便两个环境字符串相对应。For example, when you call _putenv, a call to _wputenv is also executed automatically so that the two environment strings correspond.

小心

在极少数情况下,当运行时系统同时保留环境的 Unicode 版本和多字节版本时,两个环境版本可能不完全对应。In rare instances, when the run-time system is maintaining both a Unicode version and a multibyte version of the environment, the two environment versions may not correspond exactly. 这是因为,虽然任何唯一的多字节字符字符串将映射到唯一的 Unicode 字符串,但从唯一的 Unicode 字符串到多字节字符字符串的映射却不一定是唯一的。This happens because, although any unique multibyte-character string maps to a unique Unicode string, the mapping from a unique Unicode string to a multibyte-character string is not necessarily unique. 有关详细信息,请参阅 _environ、_wenvironFor more information, see _environ, _wenviron.

备注

_Putenv_s_getenv_s系列的函数不是线程安全。The _putenv_s and _getenv_s families of functions are not thread-safe. _getenv_s无法返回字符串指针时 _putenv_s修改字符串,从而导致随机失败。_getenv_s could return a string pointer while _putenv_s is modifying the string and thereby cause random failures. 确保对这些函数的调用同步。Make sure that calls to these functions are synchronized.

在 C++ 中,这些函数的使用由模板重载简化;重载可以自动推导出缓冲区长度,从而不再需要指定大小自变量。In C++, use of these functions is simplified by template overloads; the overloads can infer buffer length automatically and thereby eliminate the need to specify a size argument. 有关详细信息,请参阅安全模板重载For more information, see Secure Template Overloads.

一般文本例程映射Generic-Text Routine Mappings

TCHAR.H 例程TCHAR.H routine 未定义 _UNICODE 和 _MBCS_UNICODE & _MBCS not defined 已定义 _MBCS_MBCS defined 已定义 _UNICODE_UNICODE defined
_tgetenv_s_tgetenv_s getenv_sgetenv_s getenv_sgetenv_s _wgetenv_s_wgetenv_s

若要检查或更改的值TZ环境变量,使用getenv_s_putenv,和 _tzset、 所需的方式。To check or change the value of the TZ environment variable, use getenv_s, _putenv, and _tzset, as required. 有关详细信息TZ,请参阅_tzset_daylight、 _dstbias、 _timezone 和 _tznameFor more information about TZ, see _tzset and _daylight, _dstbias, _timezone, and _tzname.

要求Requirements

例程Routine 必需的标头Required header
getenv_sgetenv_s <stdlib.h><stdlib.h>
_wgetenv_s_wgetenv_s <stdlib.h> 或 <wchar.h><stdlib.h> or <wchar.h>

有关其他兼容性信息,请参阅 兼容性For additional compatibility information, see Compatibility.

示例Example

// crt_getenv_s.c
// This program uses getenv_s to retrieve
// the LIB environment variable and then uses
// _putenv to change it to a new value.

#include <stdlib.h>
#include <stdio.h>

int main( void )
{
   char* libvar;
   size_t requiredSize;

   getenv_s( &requiredSize, NULL, 0, "LIB");
   if (requiredSize == 0)
   {
      printf("LIB doesn't exist!\n");
      exit(1);
   }

   libvar = (char*) malloc(requiredSize * sizeof(char));
   if (!libvar)
   {
      printf("Failed to allocate memory!\n");
      exit(1);
   }

   // Get the value of the LIB environment variable.
   getenv_s( &requiredSize, libvar, requiredSize, "LIB" );

   printf( "Original LIB variable is: %s\n", libvar );

   // Attempt to change path. Note that this only affects
   // the environment variable of the current process. The command
   // processor's environment is not changed.
   _putenv_s( "LIB", "c:\\mylib;c:\\yourlib" );

   getenv_s( &requiredSize, NULL, 0, "LIB");

   libvar = (char*) realloc(libvar, requiredSize * sizeof(char));
   if (!libvar)
   {
      printf("Failed to allocate memory!\n");
      exit(1);
   }

   // Get the new value of the LIB environment variable.
   getenv_s( &requiredSize, libvar, requiredSize, "LIB" );

   printf( "New LIB variable is: %s\n", libvar );

   free(libvar);
}
Original LIB variable is: c:\vctools\lib;c:\vctools\atlmfc\lib;c:\vctools\PlatformSDK\lib;c:\vctools\Visual Studio SDKs\DIA Sdk\lib;c:\vctools\Visual Studio SDKs\BSC Sdk\lib
New LIB variable is: c:\mylib;c:\yourlib

请参阅See also

进程和环境控制Process and Environment Control
环境常量Environmental Constants
_putenv、_wputenv_putenv, _wputenv
_dupenv_s、_wdupenv_s_dupenv_s, _wdupenv_s