Getting terminal width in C?

后端 未结 8 664
自闭症患者
自闭症患者 2020-11-22 16:07

I\'ve been looking for a way to get the terminal width from within my C program. What I keep coming up with is something along the lines of:

#include 

        
相关标签:
8条回答
  • 2020-11-22 17:03

    Here are the function calls for the already suggested environmental variable thing:

    int lines = atoi(getenv("LINES"));
    int columns = atoi(getenv("COLUMNS"));
    
    0 讨论(0)
  • 2020-11-22 17:05

    Have you considered using getenv() ? It allows you to get the system's environment variables which contain the terminals columns and lines.

    Alternatively using your method, if you want to see what the kernel sees as the terminal size (better in case terminal is resized), you would need to use TIOCGWINSZ, as opposed to your TIOCGSIZE, like so:

    struct winsize w;
    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
    

    and the full code:

    #include <sys/ioctl.h>
    #include <stdio.h>
    #include <unistd.h>
    
    int main (int argc, char **argv)
    {
        struct winsize w;
        ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
    
        printf ("lines %d\n", w.ws_row);
        printf ("columns %d\n", w.ws_col);
        return 0;  // make sure your main returns int
    }
    
    0 讨论(0)
提交回复
热议问题