使用 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
code> 被调用,更好的方法是:
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 以实现可移植性)。
关于c - 运行一个函数并检查另一个函数是否已经使用 C 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55230376/