C++ main() 的第三个环境变量参数有什么用?

2022-01-16 00:00:00 environment-variables main c++

我已经明白 char **envpmain 的第三个参数,并且在下面的代码的帮助下,我能够看到它实际上包含.

I have come to understand that char **envp is the third argument to main, and with the help of the code below, I was able to see what it actually contains.

int main(int argc, char *argv[], char *env[])
{
  int i;
  for (i=0 ; env[i] ; i++)
    std::cout << env[i] << std::endl;
  std::cout << std::endl;
}

我的问题是:为什么(在什么情况下)程序员需要使用这个?对于这个论点的作用,我已经找到了很多what 的解释,但是没有什么能告诉我这个论点通常在哪里使用.试图了解这可能用于什么样的现实世界情况.

My question is: why (in what situations) would programmers need to use this? I have found many explanations for what this argument does, but nothing that would tell me where this is typically used. Trying to understand what kind of real world situations this might be used in.

推荐答案

它是一个包含所有环境变量的数组.例如,它可以用于获取当前登录用户的用户名或主目录.一种情况是,例如,如果我想在用户的主目录中保存一个配置文件,并且我需要获取 PATH;

It is an array containing all the environmental variables. It can be used for example to get the user name or home directory of current logged in user. One situation is, for example, if I want to hold a configuration file in user's home directory and I need to get the PATH;

int main(int argc, char* argv[], char* env[]){

std::cout << env[11] << '
';  //this prints home directory of current user(11th for me was the home directory)

return 0;
}

env 的等价物是 char* getenv (const char* name) 更容易使用的函数,例如:

Equivalent of env is char* getenv (const char* name) function which is easier to use, for example:

 std::cout << getenv("USER");

打印当前用户的用户名.

prints user name of current user.

相关文章