Search code examples
cncurses

Why printw does display in this case?


Why in this case, printw displays "Blah" ? I use nocbreak. So printw is not supposed to produce output normally, because the output is line-buffered.

int main(int ac, char **av)
{
    initscr();
    nocbreak();
    printw("Blah");
    refresh();
    while (1);
}

Solution

  • It is because of the call to refresh.

    The refresh man page does not explicitly state it, but it seems to apply the buffered outputs as well.

    Without the call to refresh, no output is shown.

    If you add a call to getch instead of refresh, you get the output too, because getch does a wrefresh. Man page:

    If the window is not a pad, and it has been moved or modified since the last call to wrefresh, wrefresh will be called before another character is read.

    To see the different behavior for inputs in cbreak/nocbreak mode, you can use this program:

    int main(int ac, char **av)
    {
        char c, i;
        initscr();
        noecho();  // switch off display of typed characters by the tty
    
        printw("cbreak\n");
        cbreak();
        for (i = 0; i < 5; ++i) {
            c = getch();
            printw("%c", c);
        }
    
        printw("\nnocbreak\n");
        nocbreak();
        for (i = 0; i < 5; ++i) {
            c = getch();
            printw("%c", c);
        }
    
        return 0;
    }
    

    In cbreak mode, the program sees the five input characters as you type them (and outputs immediately due to getch). In nocbreak mode, they will be received and output only after you press return.