Saturday, 29 July 2017

c++ - ofstream is open, but does not write




I'm attempting to write data to a file using ofstream, but even though the stream is open, the files are being created (the folder has already been created), there are "endl"s or "\n"s are the end of every line, and I'm flushing the file, the text does not display in any text editor.



Here is the basis of the code:



#include 
#include
#include

int main(int argc, char ** argv) {


ofstream outputData;
stringstream stringFix;
char fileBase[150] = "./Output/outputData";
stringFix << time(NULL) << ".txt";
outputData.open(strcat(fileBase, stringFix.str().c_str()));

outputData.open(fileBase);

assert(outputData.is_open());


while (...) {
//Some data is written to the stream, similar in format to:
outputData << "Trump: " << trumpSuit << endl;
}

outputData.flush();
outputData.close();

cout << "Should have written successfully..." << endl;


}


I've seemingly tried every variation--both with the flushing and without, with "endl"s and "\n"s... For reference, trumpSuit is an enum, and so it should print out an integer, as it previously did when I used cout.



Does anyone have any insight on to what I'm forgetting?


Answer



You are opening your stream twice



char fileBase[150] = "./Output/outputData";

stringFix << time(NULL) << ".txt";
outputData.open(strcat(fileBase, stringFix.str().c_str()));

outputData.open(fileBase); // <<<<< second open here


All you write operations will output to the file named ./Output/outputData and not to ./Output/outputData.txt as I assume you have expected.



The 1st open() will create the file, but it's left empty.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...