0

I'm running simulations using C++, and to track the simulation progress I'm writing outputs as std::cout << "\rSimulation progress: " << progress;, as per this answer https://stackoverflow.com/a/3057994/4237753. So with "\r" I thought I was overriding the previous line, but when I save the output to log files, the previously overridden lines are saved as well, with a ^M before each instance of the "overridden" lines. Now I have log files that are around 100MB when they would only need to be a few KB.

An example of what the file looks like:

^MSimulation progress: 66.500^MSimulation progress: 66.600^MSimulation 
progress: 66.700^MSimulation progress: 66.800^MSimulation progress: 
66.900^MSimulation progress: 67.000^MSimulation progress: 67.100^MSimulation 
progress: 67.200^MSimulation progress: 67.300

What I want for this line is only the last instance

Simulation progress: 67.300

Is there a good way or a standard way to remove the lines for real?

Thanks!

Community
  • 1
  • 1
woodenflute
  • 325
  • 2
  • 7
  • 1
    Writing `\r` to `std::cout` does not magically remove previously written text to the file. C++ does not work this way. To do this, you have to use `seekp`() to reset the output position in the file, so that subsequent writes overwrite the existing contents. – Sam Varshavchik Apr 27 '17 at 11:02

2 Answers2

2

\r is an an output control symbol. When you write \r to file it is only an additional symbol in it.

You can't override the line in a file with \r.

Alex
  • 9,891
  • 11
  • 53
  • 87
2

There is none. Terminals are not standardized in any way. Just as a file they take a stream of bytes, but they can react differently to the input you give them.

I.e. some are able to color using escape syntax. It just happens, that a terminal you are using treats \r to go back to beginning of the line and start over writing. For the file output it's just a byte to write with out any special meaning. You are not even guaranteed that \r will reset line on every terminal you run it. It is system depended.

My best advice it to decouple your UI and your log. Those are generally a different things. You don't have to put the same information into the file and the screen.

To be able to make the file stream behaviour coherent with terminal, would require to write custom fstream buffer, which would recognize \r and seek-back to last \n. It does not sound too reasonable.

luk32
  • 15,812
  • 38
  • 62