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

C语言逐词读取文件至EOF失败:仅读部分单词求排查

问题

我编写了C语言代码,意图通过while循环逐词读取Cauchy.txt文件直至EOF,但程序仅读取了文件中的部分单词。以下是我的代码、文件内容及程序输出,恳请指点问题所在:

文件Cauchy.txt内容

Baron Augustin-Louis Cauchy was a French mathematician reputed as a pioneer of analysis. He was one of the
first to state and prove theorems of calculus rigorously, rejecting the heuristic principle of the generality
of algebra of earlier authors. He almost singlehandedly founded complex analysis and the study of permutation
groups in abstract algebra. A profound mathematician, Cauchy had a great influence over his contemporaries and
successors. His writings range widely in mathematics and mathematical physics.

More concepts and theorems have been named for Cauchy than for any other mathematician (in elasticity alone
there are sixteen concepts and theorems named for Cauchy). Cauchy was a prolific writer; he wrote approximately
eight hundred research articles and five complete textbooks.

我的代码

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<errno.h>

int main()
{
    char MyString[30];

    char fname[] = "Cauchy.txt";   // File name for reading data

    FILE* finp;  // File pointer

    // The next line specifies the complete path
    finp = fopen("C:\CodingC\exercise 3\ReadCauchy\Cauchy.txt", "r");

    int status = fscanf(finp, "%s", &MyString[0]);
    // Read a few words from the input file
    if ((finp = fopen(fname, "r")) == NULL) {
        fprintf(stderr, "File %s not found\n", fname);
    }
    else {
        fprintf(stdout, "Reading file %s\n", fname);
        do {
            fscanf(finp, "%s", &MyString[0]);
            fprintf(stdout, "%s\n", MyString);
        }
        while (fscanf(finp, "%s", &MyString[0]) != EOF);
    }

    system("pause");
        return 0;
}

程序输出

Reading file Cauchy.txt
Baron
Cauchy
a
mathematician
as
pioneer
analysis.
was
of
first
state
prove
of
rigorously,
the
principle
the
of
of
authors.
almost
founded
analysis
the
of
groups
abstract
A
mathematician,
had
great
over
contemporaries
successors.
writings
widely
mathematics
mathematical
More
and
have
named
Cauchy
for
other
(in
alone
are
concepts
theorems
for
Cauchy
a
writer;
wrote
eight
research
and
complete
textbooks.
Press any key to continue . . .

问题分析与解决

核心问题:重复读取导致单词丢失

代码里的do-while循环逻辑错误:

  • do块中调用一次fscanf读取单词并打印
  • while条件里又调用一次fscanf读取下一个单词,但这次读取的结果没有被打印,仅用来判断是否到EOF
  • 相当于每两次读取只输出一次,直接丢失了一半的单词

其他次要问题

  1. 重复打开文件:先通过绝对路径打开文件,之后又用相对路径重新打开,第一次打开的文件指针未关闭,造成资源泄漏
  2. 未检查文件打开状态:第一次打开文件后未判断finp是否为NULL,若路径错误会直接调用fscanf导致程序崩溃
  3. 路径转义错误:Windows路径中的\需要转义为\\,否则\C、\e等会被当作转义字符处理,导致路径解析失败
  4. 冗余头文件:math.h和errno.h在这段代码中未被使用,可移除

修正后的代码

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

int main()
{
    char MyString[30];
    char fname[] = "Cauchy.txt";
    FILE* finp;

    // 打开文件并检查是否成功
    if ((finp = fopen(fname, "r")) == NULL) {
        fprintf(stderr, "File %s not found\n", fname);
        system("pause");
        return 1;
    }

    fprintf(stdout, "Reading file %s\n", fname);
    
    // 正确逻辑:读取一次、判断一次、打印一次
    while (fscanf(finp, "%s", MyString) != EOF) {
        fprintf(stdout, "%s\n", MyString);
    }

    // 关闭文件,避免资源泄漏
    fclose(finp);
    system("pause");
    return 0;
}

说明

  • 改用while循环,先读取单词,判断是否到达EOF,再打印,确保每个读取到的单词都能输出
  • 移除重复打开文件的代码,添加fclose关闭文件释放资源
  • 若需使用绝对路径,需将路径写成"C:\\CodingC\\exercise 3\\ReadCauchy\\Cauchy.txt"
  • 移除无用头文件,文件打开失败时直接返回错误码,避免后续无效操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:05:33