简体   繁体   中英

Controlling the cursor while displaying the output of a C program in Linux

I am writing a C program which is to be executed on the Linux terminal. The program goes into an infinite loop and prints five lines over and over again. How do I get the cursor back to the previous lines?

Eg I want to print the alphabets and replace them every 15 seconds. So, at T=0, output is

sh>./a.out
AA
BB
CC
DD
EE

At T=15, output is

sh>./a.out
FF
GG
HH
II
JJ

I tried to use lseek over STDOUT to make it overwrite the previous text. But I guess the terminal does not support lseek. Do I have to tinker with the driver APIs? Or is there a simpler way to do that?

诅咒

您需要一个curses库,例如ncurses

There is no easy way to do what you want. Think of stdout as a continuous sheet of paper that is impossible to pull back. Once you print a line, that's it. No more changes to that line.

You can "transform stdout" to a different kind of printer, by using specific libraries (curses is common) not defined by the Standard.

Running in a Linux terminal, you should be able to use the '\\r' character which is a carriage return (without the new line). It will overwrite what was there before.

Try something like :

#include <stdio.h>

int main(void)
{
    printf("AA BB CC");
    fflush(stdout);
    sleep(3);
    printf("\rDD EE FF");
    fflush(stdout);
    sleep(3);
    printf("\n");

    return 0;
}

With that, you should be able to do whatever you want in your loop...

Edit... using ncurses :

#include <stdio.h>
#include <ncurses.h>

int main(void)
{

    initscr();
    noecho();
    raw();

    printw("AA\nBB\nCC\n");
    refresh();
    sleep(3);
    mvwprintw(stdscr, 0, 0, "DD\nEE\nFF\n");
    refresh();
    sleep(3);

    endwin();

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM