Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment Variables are in a char* how to get it to a std::string

I am retrieving the environment variables in win32 using GetEnvironmentStrings(). It returns a char*.

I want to search this string(char pointer) for a specific environmental variable (yes I know I can use GetEnvironmentVariable() but I am doing it this way because I also want to print all the environment variables on the console aswell - I am just fiddling around).

So I thought I would convert the char* to an std::string & use find on it (I know I can also use a c_string find function but I am more concerned about trying to copy a char* into a std::string). But the following code seems to not copy all of the char* into the std::string (it makes me think there is a \0 character in the char* but its not actually the end).

char* a = GetEnvironmentStrings();
string b = string(a, sizeof(a));
printf( "%s", b.c_str() );  // prints =::= 

Is there a way to copy a char* into a std::string (I know I can use strcpy() to copy a const char* into a string but not a char*).

like image 680
Mack Avatar asked Jun 12 '11 11:06

Mack


2 Answers

You do not want to use sizeof() in this context- you can just pass the value into the constructor. char* trivially becomes const char* and you don't want to use strcpy or printf either.

That's for conventional C-strings- however GetEnvironmentStrings() returns a bit of a strange format and you will probably need to insert it manually.

const char* a = GetEnvironmentStrings();
int prev = 0;
std::vector<std::string> env_strings;
for(int i = 0; ; i++) {
    if (a[i] == '\0') {
        env_strings.push_back(std::string(a + prev, a + i));
        prev = i;
        if (a[i + 1] == '\0') {
            break;
        }
    }
}
for(int i = 0; i < env_strings.size(); i++) {
    std::cout << env_strings[i] << "\n";
}
like image 64
Puppy Avatar answered Nov 03 '22 12:11

Puppy


sizeof(a) in what you have above will return the size of char*, i.e. a pointer (32 or 64bits usually). You were looking for function strlen there. And it's not actually required at all:

std::string b(a);

should be enough to get the first environment variable pair.

like image 38
Mat Avatar answered Nov 03 '22 12:11

Mat