From 481f9ba1aee62fea092184f2243d210a8686781f Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Thu, 14 Jun 2018 18:13:04 +0200 Subject: Add portable environment variable manipulation functions --- libbutl/utility.cxx | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'libbutl/utility.cxx') diff --git a/libbutl/utility.cxx b/libbutl/utility.cxx index 8e2422aa..502586c 100644 --- a/libbutl/utility.cxx +++ b/libbutl/utility.cxx @@ -10,6 +10,8 @@ #include #endif +#include // setenv(), unsetenv(), _putenv() + #ifndef __cpp_lib_modules #include #include @@ -124,6 +126,36 @@ namespace butl return l; } + + void + setenv (const string& name, const string& value) + { +#ifndef _WIN32 + if (::setenv (name.c_str (), value.c_str (), 1 /* overwrite */) == -1) + throw_generic_error (errno); +#else + // The documentation doesn't say how to obtain the failure reason, so we + // will assume it to always be EINVAL (as the most probable one). + // + if (_putenv (string (name + '=' + value).c_str ()) == -1) + throw_generic_error (EINVAL); +#endif + } + + void + unsetenv (const string& name) + { +#ifndef _WIN32 + if (::unsetenv (name.c_str ()) == -1) + throw_generic_error (errno); +#else + // The documentation doesn't say how to obtain the failure reason, so we + // will assume it to always be EINVAL (as the most probable one). + // + if (_putenv (string (name + '=').c_str ()) == -1) + throw_generic_error (EINVAL); +#endif + } } namespace std -- cgit v1.1