How can I find the width of a command line window from a GNU C++-program ?
I'll use this information to display a progress bar when copying files, so I need to know the width to be able to display the progress bar correctly.

You can use the command "stty -a" and parse out the number of columns. Example, in my command-line window stty -a shows this:

speed 38400 baud; rows 50; columns 132; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = M-^?; eol2 = M-^?; swtch = M-^?; start = ^Q; stop = ^S; susp = ^Z;
rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 hupcl -cstopb cread -clocal -crtscts -cdtrdsr
-ignbrk brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc ixany imaxbel iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke

Note the "columns 132" entry. That says that my window is 132 characters wide.

Edited 1 Year Ago by Dani: Formatting fixed. Note we do not support [CODE] bbcode. Please use Markdown syntax.

stty is not the best option for this.

You should first look to see if the environment variable $COLUMNS exists. It is most likely to be correct.

Failing that, use the command tput cols to query the terminal size.

If you really want to do it properly though you'll have to use ioctl() with TIOCGWINSZ.

Hope this helps.

To expand on what Duoas mentioned about TIOCGWINSZ, here is an example:

#include <stdio.h>
#include <unistd.h>
#include <ioctl.h>
#include <termios.h>

int main () {
   struct winsize ws;
   printf ("Window width: %zd\n", ws.ws_col);
   return 0;

I just noticed that you mentioned that you are building a progress bar. I have already built a similar utility (that supports basic text, color, or GUI implementations). It uses TIOCGWINSZ to get the terminal width.

Feel free to use it as a reference or as is for your purpose. libpbar

This question has already been answered. Start a new discussion instead.