Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

c - How to get terminal window width?

I am working on embedded system using C and linux. User can connect to the device via SSH or a console serial cable. He can do this through PuTTY or Tera Term. My question is, after he is connected, how can I know his window's width? I have tried different approaches, they work if I simulate my system on a linux pc, but none of them work on the device:

  1. ioctl()

    struct winsize ws;
    ioctl(..., TIOCGWINSZ, &ws); 
    

    This method works on pc, but it always returns 0 on the device.

  2. tgetnum()

    setupterm((char *)0, 1, (int *)0);
    CGR_INT columns = tgetnum("co");
    

    This method works on pc, but it always returns 80x24 on the device.

  3. getmaxyx()

    CGR_INT xdim;
    CGR_INT ydim;
    initscr();
    refresh();
    getmaxyx(stdscr, ydim, xdim);
    

    This method works on pc, but it always returns 0 on the device

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I use this code to print a bunch of equals signs as a divider. Works on most boxes/terms I've tried. Not sure what devices you are talking about. Worth a try I guess ;-)

#include <termios.h>
#include <sys/ioctl.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
   struct winsize ws;
   ioctl(0, TIOCGWINSZ, &ws);

   int i=0;
   for(;i<10*ws.ws_col;++i) printf("=");
   printf("
");
   return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...