1

I am trying to port an application from windows to linux. In windows I have a GetEnvironmentStrings() function in windows.h which provides me the environment variables and their values in the current process in the form NAME=VALUE. For Linux I use the environ variable like this

for (char **en=environ; *en; en++)   {
    std::string str(*en)
    env.push_back(str);      //env is a vector of strings
}

still the application doesn't seem to work. In windows when I print the size of string passed to the env vector (a vector of strings) it prints the size of all the strings as 48 bytes. whereas on Linux the size is 8. The original application uses the Unicode version (GetEnvironmentStringsW) and translate the returned wide-string to an 8-bit string using a conversion function WideCharToMultiByte.

I don't have enough knowledge abt character encodings, but I guess it has something to do with the way strings are encoded. Any idea what could be going wrong?

borrible
  • 16,503
  • 7
  • 53
  • 72
Deepti Jain
  • 1,811
  • 4
  • 20
  • 29
  • Are you looking for getenv(3) and setenv(3) (http://linux.die.net/man/3/getenv)? – fork0 Jul 25 '12 at 14:48
  • You code looks fine. http://ideone.com/jUF5k How are you printing the size of the strings? – Roddy Jul 25 '12 at 14:49
  • Where does `environ` come from? – Code-Apprentice Jul 25 '12 at 15:18
  • @Code-Guru `environ` is probably from the third argument to `main(int argc, char *argv[], char *environ[])`. Or it's just the `extern char **environ` that's usually available. – bames53 Jul 25 '12 at 15:44
  • @bames53 I haven't tried to access environment variables this way in Linux, so it's new to me. I think I've used getenv() in the very few cases I wanted an environment variable. – Code-Apprentice Jul 25 '12 at 15:48

2 Answers2

0

This seems to be relevant:

Linux: where are environment variables stored?

In order to set a value to an existing environment variable, we use an assignment expression. For instance, to set the value of the "LANG" variable to "he_IL.UTF-8", we use the following command:

LANG=he_IL.UTF-8

https://help.ubuntu.com/community/EnvironmentVariables

Or, you can execute terminal commands to get the environment variables with system(). That page tells you which libraries to include and proper usage information.

Community
  • 1
  • 1
Alex W
  • 35,267
  • 10
  • 97
  • 106
0

The fact that on Windows you're getting the same size for every environment variable is pretty suspicious. I suspect that you are not printing the size correctly and that this has nothing to do with any encoding.

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> env;
    for (char **en=environ; *en; en++)   {
        std::string str(*en);
        std::cout << str.size() << '\n';
        env.push_back(str);
    }
}

http://ideone.com/If9ut

18
33
16
16
17
7
bames53
  • 83,021
  • 13
  • 171
  • 237