0
votes

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 <iostream>
#include <sstream>
#include <fstream>

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?

1
the ... in the loop's condition looks suspiciously as if it could be the source of the problem. - Dietmar Kühl
You use relative path "./Output/outputData". Are you sure that the current directory is what you expect it to be? You may want to try an absolute path to confirm. - Wojtek Surowka
The following code works: ideone.com/ylVyMx and it's almost the same as yours except for the path (which I suggest to double check as Wojtek suggested). The problem might be somewhere else. - Marco A.
Why do you open the stream twice? - Thomas Matthews
What do you expect the 2nd open outputData.open(fileBase); to do?? Your subsequent write operations wil go to the file opened there (without extension)! - πάντα ῥεῖ

1 Answers

0
votes

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.