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.

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;
   ioctl (STDOUT_FILENO, TIOCGWINSZ, &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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.