0

Why i can't use Windows Environment path shortcut with ofstream to write a sample text file ?

    \\ C:\Users\Me\AppData\Local\Temp\Test.txt

    std::string Path = "%Temp%\\Test.txt"

    ofstream myfile;
    myfile.open (Path);
    if (!myfile.is_open())
    {
     cout << "Could not create temp file." << endl;
    }
    myfile << "Hello World";
    myfile.close();

myfile.is_open() always return false, also "%%Temp%%" and "\%Temp\%" not working.

I can get Temp path by Windows API, but i don't want to use API in this application.

Thank you

Saif
  • 231
  • 3
  • 13
  • 2
    Because `ofstream::open` has not a clue what `%Temp%` means. –  Jun 08 '18 at 22:21
  • 5
    Because environment variables are expanded by the command prompt. If you want the value, get the value. Try the `getenv` function. This works too: https://stackoverflow.com/questions/9119313/how-to-get-the-temp-folder-in-windows-7 or this: https://stackoverflow.com/questions/1322442/getting-user-temporary-folder-path-in-windows – Retired Ninja Jun 08 '18 at 22:22
  • Thank you Retired Ninja, getenv() is exactly what i'm looking for – Saif Jun 08 '18 at 22:38

1 Answers1

3

The %Temp% substitution is something done by some Windows programs, not by the C++ runtime. If you want to do this, just retrieve the environment variable yourself and build up a path. Something like this'll do it, but you'll want to add some error checking:

ostringstream tempfilepath;
tempfilepath << getenv("Temp") << '/' << "Test.txt";
ostream myFile;
myFile.open(tempfilepath.str());
...etc...
Andrew
  • 166
  • 4
  • This won't compile, even were it wrapped in a function, included the relevant headers, etc. –  Jun 08 '18 at 22:34
  • Thank you Andrew, ostringstream is worked for me to convert char* getenv() to std::string – Saif Jun 08 '18 at 22:40
  • of course in Windows would be tempfilepath << getenv("Temp") << '\\' << "Test.txt"; – Saif Jun 08 '18 at 22:43
  • Note that `getenv()` could return a path that already has a leading separator on it. Since the code is running on Windows, you can use `PathCombine()` or `PathCchCombine/Ex()`, or use `boost::filesystem` or other similar library, to combine path fragments safely in a platform appropriate manner. – Remy Lebeau Jun 08 '18 at 23:47