简体   繁体   English

在Linux中显示C程序的输出时控制光标

[英]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. 我正在编写要在Linux终端上执行的C程序。 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. 例如,我想打印字母并每15秒更换一次。 So, at T=0, output is 因此,在T = 0时,输出为

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

At T=15, output is 在T = 15时,输出为

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

I tried to use lseek over STDOUT to make it overwrite the previous text. 我试图在STDOUT上使用lseek使其覆盖之前的文本。 But I guess the terminal does not support lseek. 但是我想终端不支持lseek。 Do I have to tinker with the driver APIs? 我是否必须修改驱动程序API? 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. stdout视为无法拉回的连续纸。 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. 您可以通过使用标准未定义的特定库(通常是curses)将“ stdout”转换为另一种打印机。

Running in a Linux terminal, you should be able to use the '\\r' character which is a carriage return (without the new line). 在Linux终端上运行,您应该能够使用'\\ r'字符,这是一个回车符(没有新行)。 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 : 使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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