I want to write a C program on linux which refreshes the screen continuously and updates it in real time (for example, similar to the top
command in the terminal). Can anyone point me in the right direction.
To keep it portable across terminal types, you need to use a library such as ncurses. Check out that link, its an exhaustive tutorial.
Here is a basic program that prints an ever increasing number at the top left corner of the screen:
#include <stdio.h>
#include <ncurses.h>
int main (void)
{
/* compile with gcc -lncurses file.c */
int c = 0;
/* Init ncurses mode */
initscr ();
/* Hide cursor */
curs_set (0);
while (c < 1000) {
/* Print at row 0, col 0 */
mvprintw (0, 0, "%d", c++);
refresh ();
sleep (1);
}
/* End ncurses mode */
endwin();
return 0;
}
Thats how you refresh the window. Now, if you want to display rows of data as top
does, the data you display needs to be maintained in an ordered data-structure (depending on your data, it maybe something as simple as an array or a linked list). You would have to sort the data based on whatever your logic dictates and re-write to the window (as shown in the example above) after a clear()
or wclear()
.
If you are under xterm
or VT100
compatible, you can make use of console codes, example:
#include <stdio.h>
#include <unistd.h> /* for sleep */
#define update() printf("\033[H\033[J")
#define gotoxy(x, y) printf("\033[%d;%dH", x, y)
int main(void)
{
update();
puts("Hello");
puts("Line 2");
sleep(2);
gotoxy(0, 0);
puts("Line 1");
sleep(2);
return(0);
}
You can do almost everything with escape sequences, but as pointed out in wikipedia: ncurses
optimizes screen changes, in order to reduce the latency experienced when using remote shells.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With