简体   繁体   English

C ++调用getenv(“ LINES”)或getenv(“ COLUMNS”)在Xcode中运行良好,在终端中运行时出现段错误

[英]C++ calling getenv(“LINES”) or getenv(“COLUMNS”) runs fine in Xcode, segfaults when run in terminal

I'm trying to get the window size of my program when its run in terminal. 我正在尝试在终端中运行程序时获取其窗口大小。 In Xcode, I've edited the scheme so that the LINES and COLUMNS environmental variables are set for running within Xcode, and it runs fine there. 在Xcode中,我已经编辑了方案,以便将LINESCOLUMNS环境变量设置为在Xcode中运行,并且可以在Xcode中正常运行。 But when I click the executable under Products and try running that within the Terminal, it segfaults. 但是,当我单击“产品”下的可执行文件并尝试在终端中运行该可执行文件时,它会出现段错误。 Any idea what I'm doing wrong? 知道我在做什么错吗? Does it have anything to do with my #includes ? 它与我的#includes吗? Here's my basic code: 这是我的基本代码:

#include <iostream>

using namespace std ;

int main(int argc, const char * argv[]) {

    char* r = getenv("COLUMNS") ;

    cout << r << endl ;

    return 0;
}

If it segfaults in a terminal, it's almost certainly because the environment variable does not exists, hence r will be NULL . 如果它在终端中发生段故障,几乎可以肯定是因为环境变量不存在,因此r将为NULL So your program would be better off checking for that: 因此,您的程序最好检查一下:

#include <iostream>
#include <cstdlib>

int main (int argc, const char * argv[]) {
    char *r = std::getenv ("COLUMNS");
    std::cout << ((r == NULL) ? "?" : r) << '\n';
    return 0;
}

Run the following command from a terminal and see what you get: 从终端运行以下命令,然后查看得到的结果:

echo "!$COLUMNS!"

If it's !! 如果是!! , you'll need to figure out how to get the variables set (and exported so that they appear to sub-processes), such as with: ,您需要弄清楚如何获取变量集(并导出变量以便它们出现在子流程中),例如:

COLUMNS=$(tput cols)
export COLUMNS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM