使用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
或something,它们将不同的API抽象出来以便于移植)。