I expect this simple line of code
printf("foo\b\tbar\n");
to replace “o” with “\t” and to produce the following output
fo bar
(assuming that tab stop occurs every 8 characters).
On the contrary I get
foo bar
It seems that my shell interprets \b as “move the cursors one position back” and \t as “move cursor to the next tab stop”. Is this behaviour specific to the shell in which I’m running the code? Should I expect different behaviour on different systems?
Backspace and tab both move the cursor position. Neither is truly a ‘printable’ character.
Your code says:
To get the output you expect, you need
printf("foo\b \tbar"). Note the extra ‘space’. That says:Most of the time it is inappropriate to use tabs and backspace for formatting your program output. Learn to use
printf()formatting specifiers. Rendering of tabs can vary drastically depending on how the output is viewed.This little script shows one way to alter your terminal’s tab rendering. Tested on Ubuntu + gnome-terminal:
Also see
man settermandregtabs.And if you redirect your output or just write to a file, tabs will quite commonly be displayed as fewer than the standard 8 chars, especially in “programming” editors and IDEs.
So in otherwords:
IMHO, tabs in general are rarely appropriate for anything. An exception might be generating output for a program that requires tab-separated-value input files (similar to comma separated value).
Backspace
'\b'is a different story… it should never be used to create a text file since it will just make a text editor spit out garbage. But it does have many applications in writing interactive command line programs that cannot be accomplished with format strings alone. If you find yourself needing it a lot, check out “ncurses”, which gives you much better control over where your output goes on the terminal screen. And typically, since it’s 2011 and not 1995, a GUI is usually easier to deal with for highly interactive programs. But again, there are exceptions. Like writing a telnet server or console for a new scripting language.