getenv Not Working for COLUMNS and LINES
Asked Answered
D

3

8

I am trying to get the number of columns and lines in my program. I am using the following code to do so:

...

char *cols = getenv("COLUMNS");
printf("cols: %s\n", cols);

char *lines = getenv("LINES");
printf("lines: %s\n", lines);

...

The problem is that when I run this I get null for both. Running this with other environment variables, such as PATH or USER, works fine.

What I find strange is that running echo $COLUMNS and echo $LINES from the same shell both work fine.

Why is my program unable to get these two environment variables.

Despiteful answered 23/3, 2014 at 7:42 Comment(2)
Did you try adding the definitions to /etc/environment?Pigmy
@BartoszMarcinkowski COLUMNS and LINES are automatically set by shell (at least by bash).Lucila
E
6

COLUMNS and LINES are set by the shell, but not exported, which means that they are not added to the environment of subsequently executed commands. (To verify that, examine the output of /usr/bin/env: it will show PATH and USER, but not COLUMNS and LINES.)

In the bash shell, you can call export VAR to mark a variable for export.

Alternatively, see Getting terminal width in C? for various ways to obtain the terminal width and height programmatically.

Enshroud answered 23/3, 2014 at 8:32 Comment(1)
I was trying the suggestion from the first answer getenv() as it appeared simpler. The second method worked fine.Despiteful
S
1

If you don't see $LINES and $COLUMNS, they are probably not set. The xterm manual page states they may be set, depending on system configuration.

If you want to see what environment variables are passed to your program, use this little program (which uses the third, nonstandard "hidden" parameter to main() which should be available on all IXish systems:

#include <stdio.h>

int main(int argc, char *argv[], char *envp[])
{
    while (*envp)
    {
        printf("%s\n", *envp++);
    }   
}

If you want a portable way to obtain your terminal window size, its probably best to use ioctl(..., TIOCGWINSZ, ...)

Swinford answered 23/3, 2014 at 8:14 Comment(0)
L
0

Actually, COLUMNS and LINES are shell variable, but not environment variables.

You could use env to show the list of environment variables in current shell, and set to show the list of shell variables. And you will find that environment variables are a subset of shell variables.

The answers to this question is helpful:
differnce between the shell and environment variable in bash

Lucila answered 23/3, 2014 at 8:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.