第三个环境变量在C ++ main()中的用途是什么? [英] What's the use of the third environment variable in the C++ main()?

查看:287
本文介绍了第三个环境变量在C ++ main()中的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经明白,char ** envp是main的第三个参数,在下面的代码的帮助下,我能够看到它实际包含了什么。

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++)
    cout << env[i] << endl;
  cout << endl;

 }



我的问题是:为什么(在什么情况下)需要使用这个?我发现了很多关于这个参数的解释,但没有什么可告诉我这通常是使用的。试图了解这种情况下可能使用的现实世界情况。

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] << '\n';  //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.

这篇关于第三个环境变量在C ++ main()中的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆