Search code examples
c++fileofstream

ofstream not printing despite being open


I am trying to print data to a file; however, the file that is created is empty, and nothing seems to be printed to it. I know that the file stream is open and good because my cout statements are printing what i am expecting, but for some reason, the write-file is blank when I check. Any solutions would be appreciated. Thanks.

void printToStream(std::ofstream &fileStream, std::string printString) {
    if (fileStream.is_open() && fileStream.good()) {
        std::cout << "printing to file " << std::endl;
        std::cout << printString;
        fileStream << std::flush;
        fileStream << printString;
    } else {
        printError("File not open");
    }
}

Solution

  • Move std::flush to the end of the output.

    For example like this:

        fileStream << printString << std::flush;