Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put the contents of getenv() into a string [duplicate]

Possible Duplicate:
How to read Linux environment variables in c++

How can the following be changed to do what it's supposed to do?

string s = getenv("PATH");
like image 867
node ninja Avatar asked May 03 '11 08:05

node ninja


2 Answers

std::string getEnvVar(std::string const& key)
{
    char const* val = getenv(key.c_str()); 
    return val == NULL ? std::string() : std::string(val);
}
like image 102
Purnima Avatar answered Nov 12 '22 17:11

Purnima


You have to check that the getenv succeeded first:

char const* tmp = getenv( "PATH" );
if ( tmp == NULL ) {
    //  Big problem...
} else {
    std::string s( tmp );
    //  ...
}

(Supposing I've guessed correctly with regards to "what it's supposed to do".)

like image 29
James Kanze Avatar answered Nov 12 '22 16:11

James Kanze