Accessing Environment Variables in C++

How to separately get user and system environment variables in Windows with C

ExpandEnvironmentStringsForUser (CreateEnvironmentBlock) will only use the system variables if you pass a NULL token handle but I don't think there is a function that only gives you the user variables so you have to manually read them from the registry.

Remember that there are two user variable keys in the registry: Environment and Volatile Environment. The volatile key even has sub keys on some versions of Windows.

idiomatic C++14/C++17 approach to enumerating environment variables

There is no other way to enumerate the environment variables than you have in your question or in the linked answers. The reason is that the interface to environment variables is defined in such a way that C code can access them, so you have to do it "the C way" even in C++. C++ does not define its own way to access environment variables.

Failing to set environment variable

Try it as it is shown in the text book:

They are 2 programs:

The first program prepares an environment and passes it to a second program that it also executes.

// my_exec_program.c
#include <unistd.h>

int main(void)
{
char *my_env[] = {"JUICE=peaches and apples", NULL};
execle("diner_info", "diner_info", "4", NULL, my_env);
}

The second program reads its environment and prints it.

// diner_info.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
if (argc > 1)
{
printf("Diners: %s\n", argv[1]);
}
printf("Juice env: %s\n", getenv("JUICE"));
return 0;
}

Terminal:

gerhardh@xy:~/tests$ gcc -Wall -Wextra -pedantic my_exec_program.c -o my_exec_program
gerhardh@xy:~/tests$ gcc -Wall -Wextra -pedantic diner_info.c -o diner_info
gerhardh@xy:~/tests$ ./diner_info
Juice env: (null)
gerhardh@xy:~/tests$ ./my_exec_program
Diners: 4
Juice env: peaches and apples
gerhardh@xy:~/tests$

Mixing the code and squeezing everything into one file will not work.



Related Topics



Leave a reply



Submit