I'm trying to use ofstream's open(...) to open a file for writing in C++. For some reason, if I use a char* or string built from a stringstream, it fails. In other words, my ofstream object's fail() function returns true (verified with a check and console messages). See below:
stringstream ss;
ss << DIRECTORY_PATH;
// note, DIRECTORY_PATH is a string literal with correctly escaped backslashes
ss << generateTimestamp();
// generateTimestamp() returns a timestamp as a formatted char*
ss << ".txt";
char * logPath = (char*)malloc(sizeof(char) * strlen(ss.str().c_str()) + 1);
strcpy(logPath, ss.str().c_str();
ofstream stream;
stream.open(logPath, ios::out | ios::app);
if (stream.fail())
cout << "fail";
This prints 'fail' to console. I have verified using debugger that logPath actually points to the correct, expected string; and yes, if I do a cout<< just before the line with stream.open, it prints the correct path to console as well, e.g.:
C:\Logs\2015:01:15:18:34:10.txt
But open(...) still flips the fail state and I can not write to the file. However if I populate logPath with a string literal instead, e.g.
char * logPath = "c:\\logs\\log.txt";
Then it works. Further, obviously if I put a string literal with my path directly into the open(...) then it works.
This also fails when using the timestamp generator:
stream.open(ss.str().c_str(), ios::out | ios::app);
Why? How can I get a C string / char* out of a stringstream that an ofstream open(...) call can read? Note, this also results in a fail state:
stream.open(ss.str(), ios::out | ios::app);
Further, if I build a string using the append command, that fails as well. E.g.:
string path;
path.append(DIRECTORY_PATH);
path.append(generateTimestamp());
path.append(".txt");
stream.open(path, ios::out | ios::app);
This fails, but again, when I debug or print to console (e.g. cout << path) then I get the expected path:
C:\Logs\2015:01:15:18:34:10.txt
What am I missing?