@bobnoordam

Getting an environment variable

_dupenv_s will return a pointer to an allocated buffer that contains the value of the environment variable, which makes the most basic usage form:

char* buffer;
size_t bsize;
_dupenv_s(&buffer, &bsize, "USERDOMAIN");
printf(buffer);
free(buffer);

The function is capable to return an error code if something goes horribly wrong. Note that a “not found” condition is NOT considered an error, and should be detected by buffer being NULL or the size of the buffer which will also be set to 0. Below is a version of the same function using tchar:

	errno_t errorCode;
	wchar_t* buffer;
	size_t bsize;
	errorCode = _wdupenv_s(&buffer, &bsize, _TEXT("USERDOMAIN1"));
	if (bsize != 0)
	{
		wprintf(buffer);
	}
	else
	{
		wprintf(L"Not Found");
	}		
	free(buffer);

Lastly, note that dupenv returns a duplicate, so modification of the buffer will have no effect on the orifinal environment variable. Wrapping this up in a nice little function we get:

Calling code

	wchar_t* result = env(_TEXT("USERDOMAIN"));
	if (result == NULL)
	{
		wprintf(L"Not Found");
	}
	else
	{
		wprintf(result);
	}
	free(result);

Function

wchar_t* env(wchar_t* environmentVariable)
{
	wchar_t* buffer;
	size_t bufferSize;
	errno_t errorCode;
	errorCode = _wdupenv_s(&buffer, &bufferSize, environmentVariable);
	return buffer;
}