LoginSignup
12
9

More than 5 years have passed since last update.

ターミナルの幅をC言語で取得

Posted at

linuxのlsコマンドのオプションなしの場合、出力結果の1つのファイルが二つの行に分かれてしまうことがないです。これを実現するためには、端末のサイズ内にファイル名が収まるかという判定が必要になります。どうやって端末のサイズを取得するのかという疑問が浮かんだので、調べて見ました。以下は端末サイズを取得するためだけのサンプルです。

c
#include <sys/ioctl.h>
#include <unistd.h>

static size_t line_length = 80;
int main( int argc, char *argv[] )
{
    struct winsize ws;
    // get terminal size
    if( ioctl( STDOUT_FILENO, TIOCGWINSZ, &ws ) != -1 ) {
        printf("terminal_width  =%d\n", ws.ws_col);
        printf("terminal_height =%d\n", ws.ws_row);
        if( 0 < ws.ws_col && ws.ws_col == (size_t)ws.ws_col ) {
            line_length = ws.ws_col;
        } 
    }
    return 0;
}
12
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
9