//返回一个map <string,string> 类型,对应键值name:value. map <string, string> GetEnvAll( void ) { map<string,string> SysEnv; // open registry HKEY hRoot; DWORD nRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",0,KEY_READ,&hRoot); // error happened if(nRet!=ERROR_SUCCESS) { return SysEnv; } DWORD ind = 0; // index char valuename[256]; // name buffer DWORD nsize = 255; // name buffer size DWORD k = REG_SZ; // data type char var[256]; // data buffer DWORD dsize = 255; // data buffer size // loop all values while ((nRet=RegEnumValue(hRoot,ind,valuename,&nsize,NULL,&k,(LPBYTE)var,&dsize))!=ERROR_NO_MORE_ITEMS) { ind++; nsize = 255; dsize = 255; string tempName(valuename); string tempValue(var); SysEnv[tempName] = tempValue; } RegCloseKey(hRoot); // close the registry return SysEnv; }
但是如果仅仅需要获取某一个环境变量的值,则可以用如下的函数:
string GetEnvString( string name ) { char *pName = new char[256]; ZeroMemory(pName,256); strncpy(pName,(LPCSTR)name.c_str(),256); char pBuffer[256]; DWORD ret = GetEnvironmentVariable(pName,pBuffer,256); delete[] pName; pName = NULL; if (0==ret) { return ""; } else { string strEnv(pBuffer); return strEnv; } }
No comments :
Post a Comment