在 C/C++ 中打印所有环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2085302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing all environment variables in C / C++
提问by Jacob
How do I get the list of all environment variables in C and/or C++?
如何获取 C 和/或 C++ 中所有环境变量的列表?
I know that getenv
can be used to read an environment variable, but how do I list them all?
我知道getenv
可以用来读取环境变量,但是如何将它们全部列出?
回答by Alex Brown
The environment variables are made available to main()
as the envp
argument - a null terminated array of strings:
环境变量main()
可用作envp
参数 - 一个以空字符结尾的字符串数组:
int main(int argc, char **argv, char **envp)
{
for (char **env = envp; *env != 0; env++)
{
char *thisEnv = *env;
printf("%s\n", thisEnv);
}
return 0;
}
回答by user1602017
#include<stdio.h>
extern char **environ;
int main() {
int i = 1;
char *s = *environ;
for (; s; i++) {
printf("%s\n", s);
s = *(environ+i);
}
return 0;
}
回答by Dyno Fu
I think you should check environ
. Use "man environ".
我想你应该检查一下environ
。使用“人环境”。
回答by Skizz
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:
您的编译器可能会为提供额外环境变量信息的 main 函数提供非标准扩展。MS 编译器和大多数 Unix 版本都有这个版本的 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.
其中第三个参数是环境变量信息 - 使用调试器查看格式是什么 - 可能是字符串指针的空终止列表。
回答by Alex
int main(int argc, char **argv, char** env) {
while (*env)
printf("%s\n", *env++);
return 0;
}
回答by kennytm
int main(int argc, char* argv[], char* envp[]) {
// loop through envp to get all environments as "NAME=val" until you hit NULL.
}
回答by whunmr
LPTCH WINAPI GetEnvironmentStrings(void);
http://msdn.microsoft.com/en-us/library/ms683187%28VS.85%29.aspx
http://msdn.microsoft.com/en-us/library/ms683187%28VS.85%29.aspx
EDIT:only works on windows.
编辑:仅适用于 Windows。
回答by Sebastiaan M
In most environments you can declare your main as:
在大多数环境中,您可以将 main 声明为:
main(int argc,char* argv[], char** envp)
envp contains all environment strings.
envp 包含所有环境字符串。
回答by Len Holgate
If you're running on a Windows operating system then you can also call GetEnvironmentStrings()
which returns a block of null terminated strings.
如果您在 Windows 操作系统上运行,那么您还可以调用GetEnvironmentStrings()
它返回一个空终止字符串块。