Any reason for first print NL, then text, then manually flush compared to print text and NL?

Viewed 42

I recently needed to debug some really old legacy code, mainly designed for some microcontroller.

In this code, all printf-calls follow the same convention:

fprintf(outfile, "\r\nFormat %d", someinteger);
fflush(outfile);

You can see, the code first prints a NL (and a CR, code was written by a Win98-veteran), then the text. At the end he manually flushes the file (sometimes stdout sometimes a normal FILE*). In my knowledge this is laborious since printing \n already flushes the handle, so the following code would be sufficient.

fprintf(outfile, "Format %d\r\n", someinteger);

Is there any reason to chose the first snippet for printing text and manually flushing the handle compared to the second snippet where the flush is implied by \n?

1 Answers

As an old dinosaur fed with Fortran IV, K&R C and Unix V7 milk, I can understand this code.

The initial \r\n ensures that whatever the console mode, the cursor will be positionned at the beginning of a line. As a serial line consoles veteran, I often saw a console left in raw mode because a full screen (read curses...) program crashed and failed to restore the cooked mode. And we have to type stty sane ^J (yes Ctrl + J and not Return which only sended a useless ^M) to recover it.

The fflush after a \n still makes sense if the output can be redirected to a file or pipe. Because the automatic flush after a \n only occur (in Unix/Linux) when output directly goes to a terminal, and not when it goes to a file or pipe. So I would say that this code assumes to be possibly used in a rather hostile environment and just does its best to ensure that the text will be readable.

Related