You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:36:01