运行 一个函数并检查是否已经使用 C 执行了另一个函数

Run a function and check if another function is already executed using C

使用 C,我想 运行 一个函数基于另一个函数。我需要检查是否执行了特定功能。如果是,那么我希望这个函数在调用时也能执行,否则不会。

我正在从文件中读取一些文本。在第一个功能中,我想阅读并打印它们。现在在第二个函数中,我需要一个条件,如果第一个函数被执行,那么 运行 也是如此。否则什么也不做。

我该怎么做?

编辑

注意:这是完整的解决方案。问题得到回答后。

我的代码在这里:

#include <stdio.h>

static int already_run = 0;

void Reading_Function(FILE **rf)
{

already_run = 1;
   *rf=fopen("file.txt","r");

   if(rf==NULL)
   {
       printf("Error in file openning.");
       return 0;
   }

    char first [120];
    fscanf(*rf,"%s",first);
    printf("Value: %s", first);

}

// this is the second function

void Second_Function(FILE *rf)
{
if (already_run)
{
    char second [50];
    fscanf(rf,"%s",second);
    printf("Value: %s", second);
}
else

    return;


}

int main()
{



  char t;
  FILE *rf;
  while(scanf("%c", &t)==1)
    {
        switch(t)
        {

        case 'f' :
        Reading_Function(&rf);

        break;

        case 's' :
          Second_Function(rf);

        break;

        }
    }
    return 0;
}

如果问题不清楚,请告诉我。谢谢

以上评论已经回答了您的问题。为简单起见,代码如下所示:

static int already_run = 0;

void Reading_Function(FILE *rf) {
  already_run = 1;
  // ...
}

void Second_Function(FILE *rf) {
  if (already_run) {
    // ...
  } else {
    // ...
  }
}

就是说,如果您要做的只是让人们打电话给 Second_Function,但是 First_Function 运行 中的东西是第一次 Second_Function调用,更好的方法是:

void Second_Function(FILE *rf) {
  static int already_run = 0;

  if (!already_run) {
    already_run = 1;

    // Initialization code goes here.  You can even split it out
    // into a second function if you want, in which case you would
    // just invoke that function here.
  }

  // ...
}

这样你就不用担心任何全局变量了。

当然,如果您的代码是多线程的,这两种方法都会失效;在这种情况下,您应该使用一次(例如 pthread_once_t, call_once, InitOnceExecuteOnce, or something 将不同的 API 抽象出来以实现可移植性)。