[英]How to list all environment variables in a c/c++ app
I know that when programming in c++ I can access individual environment variables with getenv
. 我知道用c ++编程时我可以使用getenv
访问各个环境变量。
I also know that, in the os x terminal, I can list ALL of the current environment variables using env
. 我也知道,在os x终端中,我可以使用env
列出所有当前环境变量。
I'm interested in getting a complete list of the environment variables that are available to my running c++ program. 我有兴趣获取可运行的c ++程序可用的环境变量的完整列表。 Is there ac/c++ function that will list them? 是否有列出它们的ac / c ++函数? In other words, is there a way to call env
from my c++ code? 换句话说,有没有办法从我的c ++代码调用env
?
You may be able to use the non-portable envp argument to main
: 您可以使用main
的非可移植envp参数:
int main(int argc,char* argv[], char** envp)
and as a bonus apparently on OSX
you have apple which gives you other OS supplied info: 作为一个明显在OSX
上的奖励你有苹果 ,它为您提供其他操作系统提供的信息:
int main(int argc, char **argv, char **envp, char **apple)
But what is it used for? 但它用于什么? Well, Apple can use the apple vector to pass whatever "hidden" parameters they want to any program. 好吧,Apple可以使用apple vector将任何“隐藏”参数传递给任何程序。 And they do actually use it, too. 他们确实也使用它。 Currently, apple[0] contains the path where the executing binary was found on disk. 目前,apple [0]包含在磁盘上找到执行二进制文件的路径。 What's that you say? 你说的是什么? How is apple[0] different from argv[0]? apple [0]与argv [0]有什么不同? The difference is that argv[0] can be set to any arbitrary value when execve(2) is called. 不同之处在于,当调用execve(2)时,argv [0]可以设置为任意值。 For example, shells often differentiate a login shell from a regular shell by starting login shells with the first character in argv[0] being a - 例如,shell通常通过启动登录shell来区分登录shell和常规shell,其中argv [0]中的第一个字符是 -
Use the environ
global variable. 使用environ
全局变量。 It is a null-terminated pointer to an array of strings in the format name=value
. 它是一个以null结尾的指针,指向格式为name=value
的字符串数组。 Here's a miniature clone of env
: 这是env
的微型克隆:
#include <stdlib.h>
#include <stdio.h>
extern char **environ;
int main(int argc, char **argv) {
for(char **current = environ; *current; current++) {
puts(*current);
}
return EXIT_SUCCESS;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.