简体   繁体   中英

C - keeping printed terminal output in place

I have a simple c program that is first printing information related to the users machine:

Header Info 1
Header Info 2
Header Info 3

I then print columns of data related to the above:

XX      XX      XX      XX      XX
XX      XX      XX      XX      XX
XX      XX      XX      XX      XX
XX      XX      XX      XX      XX
...

What I would like is to keep the top header information in place, then have the rest of the data print under it continuously. This way the header info does not scroll off the top of the screen. What is the easiest way to accomplish this?

EDIT: I am on linux.

Just based on your general description, you can do something like this.

#include <stdlib.h>
#include <signal.h>
#include <curses.h>

static int quit_flag;

void sigint_handler (int sig) {
    quit_flag = 1;
}

int main () {
    int i;
    WINDOW *w;
    signal(SIGINT, sigint_handler);
    w = initscr();
    scrollok(w, 1);
    wsetscrreg(w, 4, LINES-1);
    wprintw(w, "%s\n", "Info 1");
    wprintw(w, "%s\n", "Info 2");
    wprintw(w, "%s\n", "Info 3");
    wprintw(w, "%s\n", "Info 4");
    wrefresh(w);
    i = 0;
    wsetscrreg(w, 4, LINES-1);
    while (++i) {
        wprintw(w, "%d\n", i);
        wrefresh(w);
        if (quit_flag) break;
    }
    endwin();
    return 0;
}

The suggested answer has a couple of problems:

  • the call to wsetscrreg within the loop is unnecessary
  • calling endwin in the signal handler is unsafe. See the section on signal handlers in the initscr manual page.

This is a corrected version:

#include <curses.h>

int main (void) {
    int i;
    WINDOW *w;
    w = initscr();
    scrollok(w, 1);
    wsetscrreg(w, 4, LINES-1);
    wprintw(w, "%s\n", "Info 1");
    wprintw(w, "%s\n", "Info 2");
    wprintw(w, "%s\n", "Info 3");
    wprintw(w, "%s\n", "Info 4");
    wrefresh(w);
    i = 0;
    while (++i) {
        wprintw(w, "%d\n", i);
        wrefresh(w);
    }
    endwin();
    return 0;
}

Further, realizing that the return value from initscr is stdscr , the program can be simplified:

#include <curses.h>

int main (void) {
    int i;
    initscr();
    scrollok(stdscr, 1);
    setscrreg(4, LINES-1);
    printw("%s\n", "Info 1");
    printw("%s\n", "Info 2");
    printw("%s\n", "Info 3");
    printw("%s\n", "Info 4");
    refresh();
    i = 0;
    while (++i) {
        printw("%d\n", i);
        refresh();
    }
    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