views:

365

answers:

4

What's the best way to expand

${MyPath}/filename.txt to /home/user/filename.txt

or

%MyPath%/filename.txt to c:\Documents and settings\user\filename.txt

with out traversing the path string looking for environement variables directly? I see that wxWidgets has a wxExpandEnvVars function. I can't use wxWidgets in this case, so I was hoping to find a boost::filesystem equivalent or similar. I am only using the home directory as an example, I am looking for general purpose path expansion.

A: 

some weird solution until someone will propose a real one: at least on Windows you can execute "echo "+string command and read its output :)

maxim1000
+2  A: 

On Windows, you can use ExpandEnvironmentStrings. Not sure about a Unix equivalent yet.

Rob Kennedy
Thanks Rob. This gets me half way there. I guess I'll look into parsing method for non windows cases.
Dan
A: 

Some platforms and compilers allow a third parameter to the main() function pointing to the environment variables. Search your compiler documentation.

Thomas Matthews
on Unix there is no need to use the 3rd parameter of main(). Use getenv() instead.
It's not an issue of discovering what a standalone environment variable is. Dan has a string with one or more environment variable names mentioned in it along with plain text, and he wants to expand the names into their values. In Perl parlance, he wants to *interpolate* the variable names, but he doesn't want to have to parse the strings himself. Windows has an API call that handles everything automatically.
Rob Kennedy
A: 

Try getenv. Here is an example taken verbatim from cplusplus.com:

/* getenv example: getting path */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  char * pPath;
  pPath = getenv ("PATH");
  if (pPath!=NULL)
    printf ("The current path is: %s",pPath);
  return 0;
}
Pete
@Pete, the question is not how to get the value of an environment variable. The question is how to expand a string that contains an environment variable within, with out looking for and parsing out the variable to then translate it myself. Rob's answer is the correct answer for Windows, now looking for the Linux equal.
Dan