C语言如何判断test函数是否已调用、目标文件是否已打开
原代码问题分析
- 你定义的
open是普通局部变量,每次调用test()都会重新初始化为0,无法记录函数的历史调用状态 - 代码中的while循环只会执行1次,属于冗余逻辑
- 基础版本中
fopen的文件名多写了末尾的点,"input.txt."会导致找不到对应文件
正确实现方案
使用C语言的静态局部变量实现状态记录:静态局部变量的生命周期和程序一致,只会在函数第一次被调用时完成初始化,后续调用时会保留上一次修改后的值,刚好可以用来标记函数是否被调用过。
实现代码(仅判断函数是否被调用过)
#include <stdio.h> void test(){ // 静态变量仅第一次调用时初始化为0,后续调用保留修改后的值 static int has_called = 0; FILE *input; if (has_called) { printf("file is already opened.\n"); return; } input = fopen("input.txt", "r"); if (input == NULL) { printf("File wasnt opened.\n"); } else { printf("File is opened.\n"); // 后续需要使用文件指针的话,也可以把input定义为静态变量存储 } has_called = 1; }
进阶实现(仅标记文件打开成功的状态)
如果需要区分「函数被调用过但文件打开失败」和「文件已经成功打开」的状态,可以调整静态变量的逻辑:
#include <stdio.h> void test(){ static int open_success = 0; static FILE *input = NULL; if (open_success) { printf("file is already opened.\n"); return; } input = fopen("input.txt", "r"); if (input == NULL) { printf("File wasnt opened.\n"); } else { printf("File is opened.\n"); open_success = 1; } }
内容的提问来源于stack exchange,提问作者user17277981
相关产品推荐
相关产品推荐

