tlx
setenv.cpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * tlx/port/setenv.cpp
3  *
4  * Part of tlx - http://panthema.net/tlx
5  *
6  * Copyright (C) 2016-2020 Timo Bingmann <tb@panthema.net>
7  *
8  * All rights reserved. Published under the Boost Software License, Version 1.0
9  ******************************************************************************/
10 
11 #include <tlx/port/setenv.hpp>
12 
13 #include <cstdlib>
14 
15 namespace tlx {
16 
17 // Windows porting madness because setenv() is apparently dangerous.
18 #if defined(_MSC_VER)
19 
20 int setenv(const char* name, const char* value, int overwrite) {
21  if (!overwrite) {
22  size_t envsize = 0;
23  int errcode = getenv_s(&envsize, nullptr, 0, name);
24  if (errcode || envsize) return errcode;
25  }
26  return _putenv_s(name, value);
27 }
28 
29 // More porting weirdness for MinGW (32 and 64)
30 #elif defined(__MINGW32__)
31 
32 int setenv(const char* name, const char* value, int overwrite) {
33  if (!overwrite) {
34  const char* current = getenv(name);
35  if (current) return 0;
36  }
37  return _putenv_s(name, value);
38 }
39 
40 #else
41 
42 int setenv(const char* name, const char* value, int overwrite) {
43  return ::setenv(name, value, overwrite);
44 }
45 
46 #endif
47 
48 } // namespace tlx
49 
50 /******************************************************************************/
int setenv(const char *name, const char *value, int overwrite)
setenv - change or add an environment variable.
Definition: setenv.cpp:42