1
votes

If I understand correctly \b escape sequence moves the active cursor position to the left and \n inserts a newline at the cursor position. But the following example is confusing.

λ> cat hello.c                               
#include <stdio.h>

int main()
{
  printf("hello,world\b\b\b\b\bWOR");
  return 0;
}

λ> cc hello.c && ./a.out
hello,WORλ> 
λ> cat hello.c          
#include <stdio.h>

int main()
{
  printf("hello,world\b\b\b\b\bWOR\n");
  return 0;
}

λ> cc hello.c && ./a.out                     
hello,WORld
λ> 

In the first example, \b\b\b\b\b moves the cursor five positions to the left (after ,) and inserts W followed by O and R and the characters in the original string after , are omitted. But, in the second example, usage of \n alters the behaviour of b in an unexpected way. The characters in the original string are overwritten and \n is inserted at the end, rather than at the cursor position. Can someone please explain this behaviour? (Or is it terminal dependent? I have tried on two different terminals.)

1
You expect text editor like behaviour. The characters on the right of the cursor will not be moved to the next line. It is a terminal window (what have you printed is there unless you printf something else there), not the text editor.0___________
@P__J__ Can you please explain the overwriting behavior? Also, are the escape characters expanded at run-time?specdrake
@drake01: The conversion of \b to a backspace character and of \n to a new-line character occurs during program translation (compilation).Eric Postpischil

1 Answers

3
votes

In the first example, \b\b\b\b\b moves the cursor five positions to the left (after ,) and inserts W followed by O and R and the characters in the original string after , are omitted.

No, that is not what happens. First, “hello,world” is written. Then the five \b characters move the cursor position to the “w”. Then “WOR” is written, leaving “hello,WORld” in the display. Then your program ends, and the command-line shell resumes executing. It prints its prompt, “λ> ”. That overwrites the “ld”, leaving “hello,WORλ> ” in the display.

But, in the second example, usage of \n alters the behaviour of b in an unexpected way. The characters in the original string are overwritten and \n is inserted at the end, rather than at the cursor position.

Again, no. “hello,world” is written, the \b characters move the cursor to “w”, then “WOR” is written, and we again have “hello,WORld” in the display. Then the \n advances the display to the next line, leaving “hello,WORld” in the previous line.