简体   繁体   中英

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 <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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM