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

C语言使用fopen读取文件时程序冻结无报错该如何解决

问题原因

你的第一个程序运行冻结的核心原因是出现了死循环:

  • 你仅在进入while循环前调用了1次fgetc(file)读取文件的第一个字符
  • 循环体内部只做了换行符判断和行数计数,没有继续读取文件后续字符,character变量的值永远不会更新为EOF,循环永远无法退出,导致程序假死。
修复方法

在while循环的末尾新增读取下一个字符的逻辑,每次循环都更新character的值即可。

修复后的完整代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void find_word (void);    

int main (int argc, char *argv[])
{
    find_word();
    return 0;    
}     

void find_word (void)
{
    FILE *file;
    int character;
    int line_number;

    file = NULL; 
    character = 0;
    line_number = 0;
    
    file = fopen ("word_source.txt", "r");
    if (file == NULL)
    {
        printf("Error\n");
        exit(0);
    }

    character = fgetc(file);
    while (character != EOF)
    {
        if (character == '\n')
        {
            line_number++;
        }
        // 新增:读取下一个字符,更新character的值
        character = fgetc(file);
    }

    fclose(file);
    // 加换行符避免输出和终端提示符粘连
    printf("%d\n", line_number);
}

补充说明:你原代码开头的printf("%c", character);无实际作用(此时character值为0,打印的是空字符),可以直接删除。

内容的提问来源于stack exchange,提问作者zelph14

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:15:03