我们在开发过程中,经常需要确认某一个环境变量的实际情况,与其使用各种echo命令去查,不如直接输出。
其实很简单,自己写个程序,调用一个Win32的API就搞定了,不过我考虑到一些安全性问题,做了一点点改进:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
int _tmain()
{
LPTSTR lpszVariable;
LPTCH lpvEnv;
// Get a pointer to the environment block.
lpvEnv = GetEnvironmentStrings();
// If the returned pointer is NULL, exit.
if (lpvEnv == NULL)
{
_tprintf(TEXT("GetEnvironmentStrings failed (%d)\n"), GetLastError());
return 0;
}
// Variable strings are separated by NULL byte, and the block is
// terminated by a NULL byte.
lpszVariable = (LPTSTR)lpvEnv;
while (*lpszVariable)
{
_tprintf(TEXT("%s\n"), lpszVariable);
size_t len = 0;
HRESULT hr = StringCchLength(lpszVariable, 1024, &len);
if (SUCCEEDED(hr))
{
lpszVariable += len + 1;
}
else
{
_tprintf(TEXT("StringCchLength failed (0x%x)\n"), hr);
break;
}
}
FreeEnvironmentStrings(lpvEnv);
return 1;
}
是不是很简单?
来,有图有真相: