JJ Jones
JJ Jones

Reputation: 101

Append to text file is not working correctly in a loop

The following code is a function that is being called multiple times under runtime. The function contains a for loop where some text is written to a stringstream buffer. The problem is that only the data from the first (or last?) function call is inputed into the text file. I am having trouble to find a way to let the data append to the text file without anything being overwritten, just in a "one after another" manner.

void testItems(const TestObjectList* const testObject) {

      std::stringstream objectOutputBuffer;
      std::ofstream fileOutput("testlog.txt", std::ios_base::app | std::ios_base::out);

      for (itr = testobjects.begin(); itr != testobjects.end(); itr++){

         objectOutputBuffer << some stuff getting written to the buffer in the loop << std::endl;

      }
      fileOutput << objectOutputBuffer.str() << "\n";
      //fileOutput.close();
}

Upvotes: 0

Views: 477

Answers (2)

Justin Randall
Justin Randall

Reputation: 2278

You actually don't need to specify the std::ios::out flag with a std::ofstream object since it already is set by default. If you want to be able to append to the end of your file all you should really need to do is set the std::ios::app flag.

std::ofstream fileOutput("testlog.txt", std::ios::app);

Also while I don't think this is your problem, the newline character doesn't flush your stringstream buffer and force it to write to the file. I would recommend replacing your "\n" with std::endl which does flush the buffer just to be sure.

Upvotes: 0

Pado
Pado

Reputation: 1637

Your fileOutput.close() is commented out, closing the file will probably fix.

Try to execute this:

int main() {
        std::ofstream f("f.txt");
        f << "this will be there\n";

        std::ofstream g("f.txt");
        g << "this will not\n";
}

The first string will be written to the file but not the second.

I suggest you to move the std::ofstream fileOutput("testlog.txt", std::ios_base::app | std::ios_base::out) outside the function and then pass fileOutput as parameter when you call it.

And when you are finished remember to close the file.

Upvotes: 1

Related Questions