Hi all,
I apologize if this is somewhere on here. I've looked some and I can't find it here or anywhere on the internet. With all the bright minds on this board, someone's bound to have an idea...

What I would like to do is open a file using the fstream class, but the pathname is going to be computer independent. In other words, I would like to call something of the following sort:

ifstream file("%APPDATA%\\Folder\\file.txt");
//do stuff...

Unfortunately, whenever I try using %APPDATA% or %HOMEPATH%, it seems to be sending something else to the ifstream's open method.

Any ideas/suggestions?
I appreciate any and all help - Thanks!

10 Years
Discussion Span
Last Post by Narue

Environment variables aren't expanded in string literals. You need to call something like getenv to get the value:

#include <cstdlib>


const char *appdata = std::getenv ( "APPDATA" );

if ( appdata != 0 ) {
  std::string path = appdata;

  path += "\\Folder\\file.txt";

  std::ifstream file ( path.c_str() );


OH YEA! Thanks, Narue. I remember seeing the getenv function used somewhere else, but it's been a little while since I've done any actual c/c++ coding. Lately it's been mostly Java. But hey, Thanks again!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.