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

C语言跨文件词频统计仅首个目标词计数正常其余为0如何解决

问题根因

你代码的核心问题是 file1的文件指针未重置:

  • 第一轮外层循环处理第一个目标单词时,内层while(fscanf(file1...))已经把file1的内容从头到尾读完了,文件指针停在了文件末尾(EOF位置)
  • 后续外层循环处理第二个、第三个目标单词时,内层fscanf读取已经在EOF位置的file1会直接返回EOF,不会执行任何统计逻辑,所以结果永远是0

其他潜在问题

  • 你只把待匹配的check_words转成了小写,但是从file2读取的目标单词words没有做小写转换,大小写不一致时会匹配失败
  • 用%s读取字符串没有限制长度,当遇到长度超过19的单词时会溢出20字节的字符数组,触发内存越界问题

修正后的代码

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

void count_words(FILE *file1, FILE *file2){
    char words[20], check_words[20];
    int occurrences = 0;

    while (fscanf(file2, "%19s", words) != EOF){
        // 目标单词也转成小写,保证大小写不敏感匹配
        for (int i=0; i<strlen(words); i++){
            words[i] = tolower(words[i]);
        }
        // 每次统计新单词前,把file1指针重置到文件开头
        rewind(file1);
        occurrences = 0;
        while (fscanf(file1, "%19s", check_words) != EOF){
            for (int i=0; i<strlen(check_words); i++){
                check_words[i] = tolower(check_words[i]);
            }
            if (strcmp(check_words, words) == 0){
                occurrences++;
            }
        }
        printf("'%s' -> %d occurrence(s)\n", words, occurrences);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:09:02