7

我正在尝试获取程序中的列数和行数。我正在使用以下代码来执行此操作:

...

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

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

...

问题是,当我运行它时,两者都为空。使用其他环境变量(例如PATHor USER)运行它可以正常工作。

我觉得奇怪的是,运行echo $COLUMNSecho $LINES从同一个 shell 都可以正常工作。

为什么我的程序无法获取这两个环境变量。

4

3 回答 3

5

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.

于 2014-03-23T08:32:08.407 回答
1

如果您没有看到$LINESand $COLUMNS,则它们可能未设置。xterm 手册页指出可以设置它们,具体取决于系统配置。

如果您想查看将哪些环境变量传递给您的程序,请使用这个小程序(它使用第三个非标准“隐藏”参数,main()所有 IXish 系统都应该提供该参数:

#include <stdio.h>

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

如果您想要一种便携式方式来获取终端窗口大小,最好使用ioctl(..., TIOCGWINSZ, ...)

于 2014-03-23T08:14:10.583 回答
0

实际上,COLUMNSandLINES是 shell 变量,而不是环境变量。

您可以使用env显示当前 shell 中的环境变量列表,以及set显示 shell 变量列表。你会发现环境变量是 shell 变量的一个子集。

这个问题的答案很有帮助:
bash 中 shell 和环境变量之间的差异

于 2014-03-23T08:40:03.337 回答