Ask the C++ Pro 10-Minute Solutions

Creating and Accessing Environment Variables
By Danny Kalev

An environment variable consists of a pair of strings: the variable itself followed by = and its associated value. For example:


PATH=C:\WINDOWS 

In DOS and Windows, you can define an environment variable from the command line or from a batch file using the command SET followed by an assignment expression. The following line creates an environment variable called VERSION whose value is 1.1.3:


SET VERSION=1.1.3  

In Unix, you omit the SET command:


VERSION=1.1.3 

Reading an Environment Variable
A program's environment is made available to it at startup. The environment consists of an array of C-strings, each in the form: "VAR=value". You access environment variables from a program using the functions getenv() and putenv().

The ANSI C function getenv() provides an easy and portable way to read an environment variable. getenv() is declared in <stdlib.h> and has the following prototype:


char * getenv(const char * name);

On success, it returns a pointer to a null-terminated char array that contains the variable's value. If the variable is not defined, getenv() returns NULL. For example:


#include <stdlib.h>
#include <stdio.h>
int main()
{
 char * descr = getenv("PATH");
 if (descr)
  printf("value of PATH is: %s", descr);
 else 
  printf("variable not defined");
}

Setting an Environment Variable
To define an environment variable or change the value of an existing variable, use the putenv() function. putenv() isn't defined by the ANSI/ISO standard. In practice, however, both Unix and Windows declare it in <stdlib.h> as a non-standard extension, so it's relatively portable. putenv() has the following prototype:


int putenv(const char * var);

The argument var must be a string in the form "VAR=VAL". putenv() adds the variable VAR to the current environment and assigns the value VAL to it. If the variable already exists, putenv() overrides the existing value. If you prefer not to override a variable's value, check whether it already exists by calling getenv() before calling putenv(). The following example adds a new environment variable called TEMP whose value is C:\TEMP (recall that a backslash must appear as a \\ inside a quoted string in C/C++). On success, putenv() returns 0, and -1 otherwise.


int stat = putenv("TEMP=C:\\TEMP");
if (!stat)
{
 printf("failed to define environment variable"); 
}

Support for Wide Character Variables
Win32 also defines wide character versions of getenv() and putenv(). Note that _wputenv() exists only on NT and Win2000:


wchar_t * _wgetenv(const wchar_t * name);
int _wputenv(const wchar_t * var);

Uses of Environment Variables
Environment variables enable you to control the program's behavior without having to make any changes to its source files or recompiling it. For instance, you can control whether a program displays debug information on the screen simply by defining an appropriate environment variable. This is particularly useful if you need to switch on debug output at a customer's site. In the following example, the program displays debug information only if the environment variable DBG is defined:


void func(); 

#include <stdlib.h>
#include <stdio.h>
int main()
{
 bool debug=false; 
 if (getenv("DBG"))
  debug=true;
 if (debug)
  printf("calling func");
 func(); 
 if (debug)
  printf("returned from func");
}

 
Other 10-Minute Solutions
 How to Change the Mouse Pointer without Flicker
 Setting Full Row Selection in ListView Control
 Automating Type Conversions with stringstream Objects
 Improving Memory Reallocation with Vectors
 How to Use <fstream> Classes for File I/O
 Casting About for Safe Typecasting
 Overloading Operator + the Right Way
 How to Create Persistent Objects
 Making Linked Lists More User-Friendly
 Preventing Glitches in Signal Processing
 Forcing Object Allocation on the Free-store
 Using String-Based Data Validation
 Implementing the 'Resource Acquisition Is Initialization' Idiom
 Simple Locks for Data Files
 Template Specializations
 Exception Handling
 Using Bit Fields in Data Optimization
 Using the Transform() Algorithm to Change a String's Case
 Use RTTI for Dynamic Type Identification
 Choosing the Right swap () Implementation
 Take Charge and Initialize Your Own Data
 Share Data Among Objects Using the Monostate Design Pattern
 String Manipulation Made Easy with std::string Algorithms
 Using typedef to Curb Miscreant Code
 Managing Objects' Construction Order
 Bitwise Operators: Combining Efficiency and Ease of Use
 Use Function Adapters to Extend Generic Algorithms' Usage
 Simplify Callback Dispatching with Enumerated Indexes
 Streamline Your Bulk I/O Operations with Stream Iterators
 Optimize Your Member Layout
 Preserve Code Safety with Conversion Operators
 Modify Your Base Class Interface in Derived Classes
 Tackle Common Programming Tasks Using the New <tuple> Library
 Use Local Classes for Proper Cleanup in Exception-enabled Apps
 Use multimap to Create Associative Containers with Duplicate Keys
 Enforcing Compile-time Constraints
 Facilitate Directory Operations with the <dirent.h> and <dir.h> Libraries
 Spruce Up Your Built-in Arrays
 Target 32- and 64-bit Platforms Together with a Few Simple Datatype Changes
 Restrict Object Allocation to Specific Memory Types
 Use the Pimpl Idiom to Reduce Compilation Time and Enhance Encapsulation
 Automate Resource Management with shared_ptr
 The Quick and Dirty Way to Add
 Pointing to Class Members
 Detecting Keystrokes While Your Application is Busy
 Linked Lists
 Programming the System Tray
 Create a "Universal" DLL
 Convert Path to Long Path Name
 Constructing an Object at a Pre-Determined Memory Position
 Declaring Classes and Member Functions in a Namespace
 Using the auto_ptr Class Template to Facilitate Dynamic Memory Management
 Using the random_shuffle() Algorithm to Randomize a Sequence of Elements
 Defining a Function Object
 Implementing the Singleton Design Pattern
 Declaring Function Pointers and Implementing Callbacks
 Overloading Operator << for a User-Defined Type
 Implementing a Stopwatch Class for Performance Measurements
 Creating and Accessing Environment Variables
 Executing an Object's Member Function in a Separate Thread
 Creating Heterogeneous Containers
 Overriding New and Delete
 Time and Date Manipulation
  Defining Functions with a Variable Argument List
 Optimize Abstract Operations with Function Templates




Sponsored Links


Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map
Jupiterweb networks

internet.comearthweb.comDevx.comClickZ

Search Jupiterweb:

Jupitermedia Corporation has four divisions:
JupiterWeb, JupiterResearch, JupiterEvents, and JupiterImages

Copyright 2004 Jupitermedia Corporation All Rights Reserved.
Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Jupitermedia Corporate Info | Newsletters | Tech Jobs | E-mail Offers