简体   繁体   English

getenv函数未返回预期答案

[英]getenv function not returning expected answer

I'm trying to access one of my environement variable, which is JAVA_HOME . 我正在尝试访问我的环境变量之一,即JAVA_HOME To do so, I'm using getenv() function, like this : 为此,我正在使用getenv()函数,如下所示:

#include <iostream>
#include <string.h>

int main() {
    const char* env = getenv("JAVA_HOME");
    if(env != NULL)
        std::cout << "Environnement : " << env << std::endl;
    else
        std::cout << "NULL" << std::endl;
    return 0;
}

I tryed std::getenv("PATH"); 我尝试了std::getenv("PATH"); which returns me something different from my file /etc/bash.bashrc where I put my JAVA_HOME variable. 这将返回与我的文件/etc/bash.bashrc不同的内容,在该文件中放置了JAVA_HOME变量。

I expected std::getenv("JAVA_HOME") to return what I put in my /etc/bash.bashrc file. 我期望std::getenv("JAVA_HOME")返回我放在/etc/bash.bashrc文件中的内容。 Now it returns something different. 现在返回不同的东西。

How can I get a correct environement variable ? 如何获得正确的环境变量? What am I doing wrong ? 我究竟做错了什么 ?

I'm under Ubuntu 12.04 with GCC 4.7.2 using C++11 with QtCreator 我在使用C ++ 11和QtCreator的Ubuntu 12.04和GCC 4.7.2下

EDIT : Code 编辑:代码

  • Include[...] was a shorthand for the includes Include [...]是include的简写

  • Added NULL handling 添加了NULL处理

EDIT : Progress 编辑:进度

  • I tryed extern char **environ but it doesn't contain the one variable I need ... 我尝试了extern char **environ但它不包含我需要的一个变量...

EDIT : Partial Solution 编辑:部分解决方案

There's not way to do such things easily as I found out. 我发现没有办法轻松地做这些事情。 I've set personal environment variables in the IDE to overcome the problem. 我已经在IDE中设置了个人环境变量来解决该问题。

Your code is fine, except that you should explicitly handle the NULL return value from getenv() . 您的代码很好,除了您应该显式处理getenv()的NULL返回值。

The issue is almost certainly with how your run the code. 问题几乎可以肯定与您如何运行代码有关。 If you: 如果你:

  1. start a shell; 启动外壳;
  2. make sure $JAVA_HOME is set correctly in that shell (through bashrc or whatever other means); 确保在该外壳中正确设置了$JAVA_HOME (通过bashrc或任何其他方式);
  3. run the executable from the shell; 从外壳运行可执行文件;

I bet it will work correctly. 我敢打赌它将正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM