954,535 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Sending a dos environment variable to fstream instance

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!

Coach_Nate
Light Poster
48 posts since Aug 2004
Reputation Points: 14
Solved Threads: 1
 

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() );

  //...
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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!

Coach_Nate
Light Poster
48 posts since Aug 2004
Reputation Points: 14
Solved Threads: 1
 

>Lately it's been mostly Java.
I'm sorry. ;)

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You