Printing all environment variables in C / C++

后端 未结 9 1624
时光说笑
时光说笑 2020-11-27 14:23

How do I get the list of all environment variables in C and/or C++?

I know that getenv can be used to read an environment variable, but how do I list th

相关标签:
9条回答
  • 2020-11-27 14:30
    int main(int argc, char* argv[], char* envp[]) {
       // loop through envp to get all environments as "NAME=val" until you hit NULL.
    }
    
    0 讨论(0)
  • 2020-11-27 14:37

    In most environments you can declare your main as:

    main(int argc,char* argv[], char** envp)
    

    envp contains all environment strings.

    0 讨论(0)
  • 2020-11-27 14:38

    The environment variables are made available to main() as the envp argument - a null terminated array of strings:

    int main(int argc, char **argv, char **envp)
    {
      for (char **env = envp; *env != 0; env++)
      {
        char *thisEnv = *env;
        printf("%s\n", thisEnv);    
      }
      return 0;
    }
    
    0 讨论(0)
  • 2020-11-27 14:43
    int main(int argc, char **argv, char** env) {
       while (*env)
          printf("%s\n", *env++);
       return 0;
    }
    
    0 讨论(0)
  • 2020-11-27 14:44

    If you're running on a Windows operating system then you can also call GetEnvironmentStrings() which returns a block of null terminated strings.

    0 讨论(0)
  • 2020-11-27 14:45

    Your compiler may provide non-standard extensions to the main function that provides additional environment variable information. The MS compiler and most flavours of Unix have this version of main:

    int main (int argc, char **argv, char **envp)
    

    where the third parameter is the environment variable information - use a debugger to see what the format is - probably a null terminated list of string pointers.

    0 讨论(0)
提交回复
热议问题