What's the use of the third, environment variable argument to the C++ main()?

前端 未结 4 455
误落风尘
误落风尘 2020-12-17 03:40

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 c

4条回答
  •  眼角桃花
    2020-12-17 04:40

    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;
    }
    

    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.

提交回复
热议问题