Since most systems, including Unix, use LF(\n
, 0x0A
) as a newline character, using of CR(\r
, 0x0D
) is quite rare. One of the few cases where CR is used in modern computers is when creating progress bars in text applications. Using CR allows for a simple implementation of progress bars in terminals.
The code above draws a progress bar with #
and '
'(space). For convenience, I fixed the progress bar's length at 20 characters, adding one # for every 5% increase in progress. When using CR to draw a progress bar like this, there are three points to consider.
The first point is to draw the progress bar on stderr
instead of stdout
. One of the significant differences between stdout
and stderr
is that stdout
buffers output rather than immediately displaying it on the screen. Typically, stdout
buffers output until it encounters a newline character. Therefore, if you print a progress bar without a newline character on stdout
, the screen will not be updated until the progress bar is complete. If you need to use stdout
for some reason, you must call the flush(stdout)
function explicitly.
The second point is that the length of the string to be printed next should not be shorter than the previously printed string. CR only moves the cursor to the beginning of the line; it does not erase the current line. While this is not a concern for fixed-length progress bars, more complex control sequences may be needed to erase the current line or use space characters to erase the remaining characters when repeatedly outputting various strings on the same line.
The last point is not to output other strings while updating the progress bar. The code above assumes that only the progress bar will be drawn until it is complete. If other strings are printed in the middle, the result will differ entirely from what was intended.
Using control sequences allows for a perfect implementation that repeatedly modifies the same line, like the progress bar. However, using control sequences for simple programs like data processing can be overkill. Using CR alone can provide a simple and efficient implementation for displaying progress in simple programs.
Comments
Post a Comment