3 Apr 2020

C++ Tips: Get All System Environment Variables

收藏到CSDN网摘

It's very common that you might need to get/edit/delete a system environment variable from time to time. In one of my previous post, I shared two functions that could get a system environment variable by its name or get all system environment variables in a map<string,string>. However, the function didn't return ALL variables if you checked here as shown in the screenshot.




In this post, I made another function that can obtain all system environment variables from the list.

map<string,string> GetAllSysEnvVars(void)
{
 map<string,string> SysEnv;

 extern char **environ;
 char **env = environ;

 while (*env)
 {
  string tempStr(*env);
  size_t pos = tempStr.find_last_of('=');
  if (pos != string::npos) {
   string tempName = tempStr.substr(0, pos);
   string tempVal = tempStr.substr(pos + 1);
   SysEnv[tempName] = tempVal;
  }
  env++;
 }
 return SysEnv;
}

No comments :

Post a Comment