LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   environment variables in c++ (https://www.linuxquestions.org/questions/programming-9/environment-variables-in-c-222522/)

s3b0 08-26-2004 01:47 AM

environment variables in c++
 
hello
how can i get environment variable value in c++ program?
thanks in advance
--
s3b0

rjlee 08-26-2004 03:38 AM

I don't think there's a specific C++ interface but you can certainly use the C mechanism.

At the top of the file, add the line [code]#include <stdlib.h>[/code>

Then, to get the environment variable:
Code:

char * var = getenv("HOME");
(Replace HOME with the variable name you want; $HOME is the user's current directory.)

Hope that helps,

— Robert J. Lee

s3b0 08-26-2004 03:47 AM

yes
that's what i was looking for:)
thanks

--
s3b0

dileepkk 08-27-2004 04:34 AM

If u want all the environmental variables, u can try this program

#include<unistd.h>
extern char **environ;
int
main()
{
int i;

for(i=0;environ[i]!=NULL;i++)
printf("%s\n",environ[i]);
return 0;
}

here environ is a global predefined variable

Dileep

rjlee 08-27-2004 05:19 AM

Or even (using C++ style I/O):

Code:

#include <iostream>
int main(int,char **,char ** envp) {
for(int i=0;envp[i]!=NULL;i++)
  std::cout << envp[i];
  return 0;
}


dileepkk 08-27-2004 09:05 AM

That is true but for that we have to give parameters to main.

x12344321 08-27-2004 09:19 AM

envp is (somewhat) depreciated. mabye not in the formal sense, but i wouldnt reccomend using it. environ is a cleaner solution.


All times are GMT -5. The time now is 08:54 PM.