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?

E.g. 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?

-------------Problems Reply------------

See curses.

You need a curses library, such as 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;
}

Category:c# Views:0 Time:2010-09-20
Tags: c# linux

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.088 (s). 11 q(s)