Get size of terminal window (rows/columns)

前端 未结 6 2102
执笔经年
执笔经年 2020-12-02 13:37

Is there any reliable way of getting the number of columns/rows of the current output terminal window?

I want to retrieve these numbers in a C/C++ program.

I

6条回答
  •  死守一世寂寞
    2020-12-02 14:02

    On GNU/Linux using libtermcap (https://www.gnu.org/software/termutils/manual/termcap-1.3/html_mono/termcap.html) create demo.c:

    #include 
    #include 
    #include 
    #include 
    
    static char term_buffer[2048];
    
    void
    init_terminal_data (void)
    {
    
      char *termtype = getenv ("TERM");
      int success;
    
      if (termtype == NULL)
        fprintf (stderr, "Specify a terminal type with `setenv TERM '.\n");
    
      success = tgetent (term_buffer, termtype);
      if (success < 0)
        fprintf (stderr, "Could not access the termcap data base.\n");
      if (success == 0)
        fprintf (stderr, "Terminal type `%s' is not defined.\n", termtype);
    }
    
    int
    main ()
    {
      init_terminal_data ();
      printf ("Got: Lines: %d, Columns: %d\n", tgetnum ("li"), tgetnum ("co"));
      return 0;
    }
    

    Then compile with gcc -o demo.x demo.c -ltermcap and run to give:

    $ ./demo.x
    Got: Lines: 24, Columns: 80
    

    I doubt this helps much on Windows though, I don't know that platform.

    (Some of this code is copied straight from the termcap documentation.)

提交回复
热议问题