Reputation: 139
Currently I discovered that I can move the cursor in the terminal output as if I'm writing in Word using "\033[A" to move the cursor in the line above and "\033[B" to below . So I tried to understand something more and I wrote these 2 lines of code in C :
#include <stdio.h>
#include <stdlib.h>
int main (){
printf("\n 2 3 \033[A \033[D 1 \033[B \n 4 5 6");
}
And this is the output :
1
2 3
4 5 6
My expectations were differents because this was my expected output
1
2 3
4 5 6
So I'm missing some informations and I think that probably I need of a character that says "go back of one positions" like "\t" but the opposite. I found this page in some old posts Here
But some characters don't work. Can someone explain me how these stuffs work? Because I tried "\033[C" and "\033[D" to move right and left but nothing.
Upvotes: 0
Views: 1938
Reputation: 1
For your expected output,
#include <stdio.h>
#include <stdlib.h>
int main (void){
printf("\n2 3\033[F1\033[B\033[B\n4 5 6");
}
This will gives you the correct result. There is no need for \033[D ( \033A \033D ~ \033A ). If you use this line it move's the cursor to current position of the previous line, it will not move backward to the beginning of the previous line. Instead you have to use \033[F.
Upvotes: 0
Reputation: 6338
These sequences are called ANSI Escape Sequences, and date back to the 1970s with the DEC VT-100 terminal, so they're still sometimes called VT-100 escape sequences. There's a list here and here.
The codes you're interested in are:
Esc[ValueA Move cursor up n lines CUU
Esc[ValueB Move cursor down n lines CUD
Esc[ValueC Move cursor right n lines CUF
Esc[ValueD Move cursor left n lines CUB
One thing you may not be accounting for is that these motions don't care "how much information" is on a given line; they just treat the screen as a grid of characters. So ESC[A goes straight up one line, even if it's "past the end" of the previous line. And so on.
So to move up one line and left two characters:
printf("\033[A\033[2D");
\033
is the ASCII code for ESC (in octal -- sometimes you'll see it in hex as \x1b
; same thing). Don't add any extra spaces or newlines; just print the codes directly.
Upvotes: 3