Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh the screen continuously and update it in real time [closed]

Tags:

c

linux

terminal

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.

like image 846
GP007 Avatar asked Aug 27 '13 06:08

GP007


2 Answers

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().

like image 154
jman Avatar answered Oct 09 '22 00:10

jman


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.

like image 20
David Ranieri Avatar answered Oct 09 '22 01:10

David Ranieri