0

我正在使用 C 来获取终端大小。该函数将在主函数中调用。然后我希望再次运行它以检查终端大小是否已更改或保持不变。这次该函数在其他函数 run_menu 中调用。有关其他信息,运行菜单也在主函数中调用。我将在代码中进行更多解释。错误是“函数'get_terminal_size'的参数太少。

//this function is to get the terminal size
//my idea is to use pointer as it will be use again in other function
void get_terminal_size(int *x, int* y)
{
    int cols,lines;
    assert(x);
    assert(y);

    #ifdef TIOCGSIZE
    ioctl(0,TIOCGSIZE, &ts);
    lines = ts.ts_lines;
    cols = ts.ts_cols;

    #elif defined(TIOCGWINSZ)
    struct winsize ts;
    ioctl(0,TIOCGWINSZ, &ts);
    lines = ts.ws_row;
    cols = ts.ws_cols;

    #endif
    *x = cols;
    *y = lines;
}

//this function is to see either the size has changed or not
int change_terminal_size()
{
    int new_cols, new_lines;
    int x, y;
    get_terminal_size(&x, &y);

    #ifdef TIOCGSIZE
    ioctl(0,TIOCGSIZE, &ts);
    new_lines = ts.ts_lines;
    new_cols = ts.ts_cols;

    #elif defined(TIOCGWINSZ)
    struct winsize ts;
    ioctl(0,TIOCGWINSZ, &ts);
    new_lines = ts.ws_row;
    new_cols = ts.ws_cols;

    #endif
    log_debug("new lines=%d,new cols =%d",new_lines,new_cols);
    if((new_cols !=x)||(new_lines != y)){
    return 1;
    }
    return 0;
}

//this function is to run the menu.
static void run_menu()
{
  //bla bla bla with other declaration and function
  //i will not write it because its not related
    while(1){
        if (change_terminal_size()){
        log_debug("the terminal has change size");
        }
  //and it will continue with other things

 //this is the main function
 int main()
 {
  //again with other declaration and function not related
  get_terminal_size();
  run_menu();
  //continue on with other thing, then return 0     
 }

如你看到的。我两次调用“get_terminal_size”函数。它与我遇到的问题有关吗?据我所知,如果我使用的是指针,那么它应该没有任何问题。

4

3 回答 3

3

在这里:

//this is the main function
int main()
{
  get_terminal_size(); //<---Right here!
  run_menu();  
}

您没有将任何参数传递给 get_terminal_size。

get_terminal_size 期望使用两个参数调用,因此会出现错误“函数参数太少”。

“使用指针”实际上与它没有任何关系,“使用指针”也不允许您从多个位置使用该函数。所有指针(x 和 y)都允许函数在其范围之外更改值。

边栏:您可能应该让 get_terminal_size 返回一个值——在这种情况下,可能是一个带有 X 字段和 Y 字段的结构。通过副作用返回值的函数更难以推理并且更可能包含错误,尽管这个特定示例可能很好,因为您没有将输入参数与输出参数混合。

您的 change_terminal_size() 函数看起来也很粗糙。您在哪里跟踪旧终端尺寸,以便将其与新终端尺寸进行比较?

于 2013-09-25T04:16:35.240 回答
2

get_terminal_size(int*, int*)是一个具有两个类型参数的函数int*。为了调用这个函数,你必须向它传递适当数量的参数,每个参数都具有正确的类型。在main中,您不带任何参数地调用它,并且您的编译器会抱怨,这是理所当然的。

main函数将需要传递一些适当的参数 - 如下所示:

 int main()
 {
  //again with other declaration and function not related
  int x = 0, y = 0;
  get_terminal_size(&x, &y); // &x and &y both have type int*
  run_menu();
  //continue on with other thing, then return 0     
 }
于 2013-09-25T04:15:37.780 回答
1

您正在调用一个带有两个参数的函数,但是在执行此操作时没有使用任何参数。您确实在 中使用了正确数量的参数change_terminal_size,这就是该函数成功的原因。

不过,好消息是,由于get_terminal_size不影响外界,您可以替换main为:

int main()
{
  run_menu();
  return 0;  
}
于 2013-09-25T04:17:38.060 回答