Home > Software engineering >  How to print lines in C terminal after u have passed the line
How to print lines in C terminal after u have passed the line

Time:02-03

I know based on the header, my question doesn't make much sense but hopefully the example might.

ex:

printf("hello world\n\n\n");
printf("hello again");
printf("bye now");
printf("this should print on line 2");
printf("this should print on line 3");
printf("this should print on line 4");

expected output
1. hello world
2. this should print on line 2
3. this should print on line 3
4. this should print on line 4
5. hello again
6. bye now

My goal is to first print out lines 1,5, and 6. And then print out lines 2-4(inclusive), with 1 second in between. I know you can print out the lines with 1 second in between using sleep. But I am not sure how to print lines 2 - 4 after printing out lines 5, and 6.

CodePudding user response:

This should do it:

#include <stdio.h>
#include <unistd.h>

int main()
{
    printf("hello world\n");
    sleep(1);
    printf("\n\n\n");
    printf("hello again\n");
    sleep(1);
    printf("bye now\n");
    sleep(1);
    printf("\033[5A");         /* move up 5 lines */
    printf("but wait\n");
    sleep(1);
    printf("there's more\n");
}

The magic, of course, is in that line

printf("\033[5A");

The sequence \033 prints the ASCII Esc character (octal 33, hex 1b). And the four-character sequence

Esc [ 5 A

moves the cursor up 5 lines.

This assumes you have a terminal (or a terminal emulator) that implements the ANSI-standard cursor motion sequences, but most of them do. (Once upon a time, there were lots of different terminals using lots of different cursor motion conventions, and it was recommended to use the termcap and/or ncurses packages to insulate your code from those details.)

These ANSI sequences aren't part of (aren't specified by) the C language, but as I say, they tend to work. The most useful is probably ESC [ rr ; cc H which will move to an arbitrary row rr and column cc. There are lots more of these sequences; one decent reference I just found is https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797 .

  •  Tags:  
  • Related