Home > Software engineering >  Move cursor escape sequence
Move cursor escape sequence

Time:10-17

I am trying to move the cursor in a terminal program using escape sequences. In the below C program, it seems like the first three commands are successful (clear screen, move cursor home, print some reference text), however the last command where I try to move the cursor to an arbitrary position fails (2,2) instead moves the cursor to the beginning of the fourth line and also clears the fourth line. What am I doing wrong?

#include <stdio.h>
#include <stdlib.h>

int main()
{
  printf("\x1b[2J"); // clear screen
  printf("\033[H"); // move cursor home
  printf("1111\n2222\n3333\n4444"); // add some text to screen for reference
  printf("\033[2;2H"); // move cursor to 2,2
  while (1); // keep program running
}

CodePudding user response:

You need to call fflush:

printf("\033[2;2H"); // move cursor to 2,2
fflush(stdout);
while (1); // keep program running

Notice that while (1); is not the correct way to keep the program running, an endless loop without a sleep will consume 100% of the CPU, instead:

while (1) sleep(1); // #include <unistd.h> for sleep()

or better yet:

getchar();
  • Related