In case you need to deal with environment variables

Published October 11, 2005
Advertisement
EnvironmentVariableMap.h

[source lang="cpp"]
#ifndef EnvironmentVariableMap_h___
#define EnvironmentVariableMap_h___

#include
#include

class EnvironmentVariableMap; // forward declaration

class EnvironmentVariable
{
friend class EnvironmentVariableMap;
std::string m_key;
EnvironmentVariable (const std::string key = "") : m_key(key) { }
public:
EnvironmentVariable& operator= (std::string& value);
operator std::string() const;

};
bool operator== (EnvironmentVariable& lhs, std::string& rhs);
bool operator== (std::string& lhs, EnvironmentVariable& rhs);

class EnvironmentVariableMap
{
private:
EnvironmentVariableMap() { }
static EnvironmentVariableMap* sm_this;
public:
static EnvironmentVariableMap& getSingleton();
static EnvironmentVariableMap* getSingletonPtr() { return sm_this; }
std::string get(const std::string& key);
void set(const std::string& key, const std::string& value);
EnvironmentVariable& operator[] (const std::string& key);
};

#endif // EnvironmentVariableMap_h___
[/source]

EnvironmentVariableMap.cpp

[source lang="cpp"]
#include
#include "EnvironmentVariableMap.h"

#if defined(__WIN32__) || defined(_WIN32)
# define putenv _putenv
#endif

using namespace std;

EnvironmentVariableMap* EnvironmentVariableMap::sm_this = 0;

EnvironmentVariableMap& EnvironmentVariableMap::getSingleton ()
{
if (0 == sm_this)
sm_this = new EnvironmentVariableMap();

return *sm_this;
}

string EnvironmentVariableMap::get(const string &key)
{
return string(getenv(key.c_str()));
}

void EnvironmentVariableMap::set(const string &key, const string &value)
{
string setline(key);
setline += "=";
setline += value;

putenv(setline.c_str());
}

EnvironmentVariable& EnvironmentVariableMap::operator[] (const string& key)
{
EnvironmentVariable* tmp = new EnvironmentVariable(key);
return *tmp;
}

EnvironmentVariable& EnvironmentVariable::operator= (string &value)
{
EnvironmentVariableMap::getSingleton().set(m_key, value);
return *this;
}

EnvironmentVariable::operator string () const
{
return EnvironmentVariableMap::getSingleton().get(this->m_key);
}

bool operator== (EnvironmentVariable &lhs, string &rhs)
{
return string(lhs) == rhs;
}

bool operator== (string &lhs, EnvironmentVariable &rhs)
{
return lhs == string(rhs);
}
[/source]

This code can possibly be improved by adding a cache for environment variables, but then any environment changes need to be made through the class. Use of EnvironmentVariableMap is easy. But it doesn't like C-style strings, since I never bothered to deal with them. You can add that, too, if you want
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Profile
Author
Advertisement
Advertisement