A use for the carriage return

·—— ···· ·· — ····· ···—— ——···

I just found out what the carriage return character, \r, is good for. A friend was asking for help on a command-line program: he wanted to update a progress indicator. This is like you get when downloading something with curl or wget or fetch. So I opened up /usr/src/usr.bin/fetch/fetch.c, expecting to find some low-level TTY hackery. Instead, I found this key line:

fprintf(stderr, "\r%-46.46s", xs->name);

It turns out that the carriage return moves the output cursor back to the beginning of the current line, so further output overwrites whatever was already there. It turns out, too, that this works from Python on both Unix and Windows:

>>> print "foo\rbar"
bar

Yay!

This makes sense if you think about where the term "carriage return" comes from, and it also makes sense out of why Windows includes it as part of its EOL indicator.I have a typewriter at home, and I've been using it lately to type invoices for the little bit of consulting that I still do. The bar on my typewriter that ends a line actually does perform two functions: first it scrolls the paper up—newline, \n. Then if you keep pushing the bar, it moves the carriage (the roller assembly that holds the paper) back to the right until you hit your first tab stop—carriage return, \r. So on my typewriter the EOL sequence is \n\r, but apparently on teletypes the order was reversed. And I actually do perform a \n without a \r sometimes, like when I'm lining up columns on an invoice. I can do a \r without a \n too, but that's a different knob.

Unlike so many Unix conventions that are the result of ossified traditions from more innocent times, it appears that the single-character EOL is actually an innovation. It's fun to know your roots.

·—— ···· ·· — ····· ···—— ——···
Feed back to Chad Whitacre.