需要帮助使用命令输出分页的ncurses在我的自定义CLI

问题描述 投票:1回答:1

我需要为我的CLI简单寻呼机命令的输出。我希望能够在输出上下滚动/,无论是在由线时间或线一整页。

我接过一看“少”的源代码,但它太复杂,帮助我。于是,我开始写我自己一个简单的问题。什么我迄今所做的是我写的命令输出到文件。然后逐行读取文件中的行,并写入ncurses的窗口。当我到了窗口的底部,我等待用户按一个键,然后清除屏幕并写下新的一页等等。其结果是一样的东西“更多”命令。

下面是简单的代码我使用:

int print()
{
    FILE *fp;
    ssize_t read;
    int row, col, x, y;
    char *line = NULL;
    char c;
    size_t len;

    initscr();
    getmaxyx(stdscr, row, col);

    fp = fopen("path_to_output_file", "r");

    if (!fp)
    {
        printf("Failed to open CLI output file.\n");
        return -1;
    }

    while ((read = getline(&line, &len, fp)) != -1)
    {
        getyx(stdscr, y, x);

        if (y == (row - 1))
        {
            printw("Press Any Key to continue...");
            c = getch();

            if (c == 'q')
            {
                break;
            }

            clear();
            move(0, 0);
        }

        printw(line);
        refresh();
    }

    fclose(fp);
    getch();
    endwin();

    return 0
}

现在我需要帮助,找到实现向后滚动到输出向上移动一页/行的想法。我应该如何遍历文件和打印线ncurses的窗口,让我想要的结果。

除此之外,任何想法提高我简单的寻呼机赞赏...

c pagination ncurses
1个回答
1
投票

虽然你已经在它的工作,这里是它利用而行读fseek()到文件(物理/窗口)线,收集开始的偏移向后移动的实现:

    …
    keypad(stdscr, TRUE);   // enable returning function key tokens
    long offset, *pos = NULL, lineno = 0;
    char buffer[col+1];
    TABSIZE = 1;
    do
    {   y = 0;
        long topline = lineno;
        while (offset = ftell(fp), line = fgets(buffer, sizeof buffer, fp))
        {
            pos = realloc(pos, (lineno+1) * sizeof *pos);   if (!pos) exit(1);
            pos[lineno++] = offset; // save offset of current line
            addstr(line);
            getyx(stdscr, y, x);
            if (y == row-1)
                break;
        }
        printw("Press [upward arrow] or [Page Up] or any key to continue...");
        int c = getch();
        if (c == KEY_UP)    // Up arrow
            fseek(fp, pos[lineno = topline>1 ? topline-1 : 0], SEEK_SET);
        else
        if (c == KEY_PPAGE) // Previous page
            fseek(fp, pos[lineno = topline>=row ? topline-row+1 : 0], SEEK_SET);
        else
        if (c == 'q' || !line)
            break;

        clear();
        move(0, 0);
    } while (1);

    fclose(fp);
    endwin();
    …

举一个简单的方法来处理与标签上的问题,我设置TABSIZE为1。

© www.soinside.com 2019 - 2024. All rights reserved.