Getting terminal width in C?

后端 未结 8 762
自闭症患者
自闭症患者 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 16:44

    To add a more complete answer, what I've found to work for me is to use @John_T's solution with some bits added in from Rosetta Code, along with some troubleshooting figuring out dependencies. It might be a bit inefficient, but with smart programming you can make it work and not be opening your terminal file all the time.

    #include 
    #include 
    #include  // ioctl, TIOCGWINSZ
    #include        // err
    #include      // open
    #include     // close
    #include    // don't remember, but it's needed
    
    size_t* get_screen_size()
    {
      size_t* result = malloc(sizeof(size_t) * 2);
      if(!result) err(1, "Memory Error");
    
      struct winsize ws;
      int fd;
    
      fd = open("/dev/tty", 0_RDWR);
      if(fd < 0 || ioctl(fd, TIOCGWINSZ, &ws) < 0) err(8, "/dev/tty");
    
      result[0] = ws.ws_row;
      result[1] = ws.ws_col;
    
      close(fd);
    
      return result;
    }
    

    If you make sure not to call it all but maybe every once in awhile you should be fine, it should even update when the user resizes the terminal window (because you're opening the file and reading it every time).

    If you aren't using TIOCGWINSZ see the first answer on this form https://www.linuxquestions.org/questions/programming-9/get-width-height-of-a-terminal-window-in-c-810739/.

    Oh, and don't forget to free() the result.

提交回复
热议问题