首页 > 解决方案 > 检查之前是否调用过函数

问题描述

这是我正在尝试使用的基本代码。

void test(){
    FILE *input;
    input = fopen("input.txt.", "r");
}

所以我试图检查文件之前是否已经打开过,这意味着之前调用过一次 void test() 函数。我真的不知道该怎么做,我尝试了while和if。像这样。

void test(){
    FILE *input;
    int open = 0;
    while (open == 0){
        input = fopen("input.txt", "r");
        if (input == NULL){
            printf("File wasnt opened.\n");
        }
        if (input != NULL){
            printf("File is opened.\n");
        }
        open = open + 1;
    }
    if(open!=0){
        printf("file is already opened.\n");
    }
}

标签: c

解决方案


使用局部静态变量。

void test (void)
{
  static bool called_before = false;

  if(called_before)
  {
    do_this();
  }
  else
  {
    do_that();
    called_before = true;
  }
}

推荐阅读