Getting terminal width in C?

转:http://stackoverflow.com/questions/1022957/getting-terminal-width-in-c

方法一:

#include <sys/ioctl.h>
#include <stdio.h>

int main (void)
{
    struct winsize w;
    ioctl(0, TIOCGWINSZ, &w);

    printf ("lines %d
", w.ws_row);
    printf ("columns %d
", w.ws_col);
    return 0;
}

方法二:

#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
#include <error.h>

static char termbuf[2048];

int main(void)
{
    char *termtype = getenv("TERM");

    if (tgetent(termbuf, termtype) < 0) {
        error(EXIT_FAILURE, 0, "Could not access the termcap data base.
");
    }

    int lines = tgetnum("li");
    int columns = tgetnum("co");
    printf("lines = %d; columns = %d.
", lines, columns);
    return 0;
}

注意:Needs to be compiled with -ltermcap . There is a lot of other useful information you can get using termcap. Check the termcap manual using info termcap for more details.

原文地址:https://www.cnblogs.com/pengdonglin137/p/3345549.html