#include #include // perror #include // for getenv, putenv, setenv, unsetenv, ... #include // errno #include // for strncmp using namespace std; void PrintAVar(string varName) { char * result; cout << "Checking the value of $" << varName << endl; result = getenv(varName.c_str()); cout << "\t"; if (result == nullptr) { cout << varName << " is not defined" << endl; } else { cout << varName << " is set to " << result << endl; } cout << endl; return; } void SetButNoMod(string name, string value) { cout << "Attempting to set (but not modify) " << name << " to be " << value << endl; if (-1 == setenv(name.c_str(), value.c_str(), 0) ) { perror("\t\tERROR setenv"); } cout << endl; return; } void SetOrMod(string name, string value) { cout << "Attempting to set or modify " << name << " to be " << value << endl; if (-1 == setenv(name.c_str(), value.c_str(), true) ) { perror("\t\tERROR setenv"); } cout << endl; return; } void FindName(string name, char ** envp, string where ) { int i; string search = name+"="; cout << "Searching " << where << " for " << name << endl; for (i=0;envp[i] != nullptr; i++) { if (0==strncmp(envp[i],search.c_str(),search.size())) { cout <<"\tFound $" << name << " at envp[ " << i << "] it is \"" << envp[i] << '"' << endl; } } cout << endl; return; } void Remove(string name) { cout << "Attempting to remove " << name << endl; if (0 != unsetenv(name.c_str())){ perror("unsetenv"); } cout << endl; return; } int main(int, char ** , char ** envp) { extern char ** environ; // show how to loop through the environment pointer FindName("HOME", envp, "envp"); // print a variable that probably exists. PrintAVar("HOME"); // print one that probably does not exist. PrintAVar("DAN"); // set a variable. SetButNoMod("DAN", "IS KING of KODE"); PrintAVar("DAN"); // try to reset with a flag of no mod SetButNoMod("DAN", "IS CING of CODE"); PrintAVar("DAN"); // reset with a mod flag = true SetOrMod("DAN", "IS CING of CODE"); PrintAVar("DAN"); // can the value contain an =, why yes, yes it can. SetOrMod("DAN", "DAN=The Best"); PrintAVar("DAN"); // but note the new value is not in envp FindName("DAN", envp, "envp"); // but it is in environ FindName("DAN", environ, "environ"); // can the variable name have an =, not it can't SetOrMod("DAN=", "DAN is the Best"); // can the variable name be "", no again! SetOrMod("", "DAN is the Best"); // Can I remove a variable? Remove("DAN"); PrintAVar("DAN"); FindName("DAN", environ, "environ"); // can I remove it again?, well, probably not, but no error. Remove("DAN"); return 0; }