这是对 fgetc 的有效使用吗?

Is this a valid use of fgetc?

我的输入流来自一个文本文件,其中包含由 \n 字符分隔的单词列表。 函数 stringcompare 是一个比较两个字符串是否相等的函数,不区分大小写。

我有两个字符串数组,word[50] 和 dict[50]。 word 是将由用户提供的字符串。 基本上我想做的是传递 word[] 和文本文件中的每个单词作为 stringcompare 函数的参数。

我已经编译 运行 这段代码,但它是错误的。大错特错。我究竟做错了什么?我什至可以像这样使用 fgetc() 吗?内部循环完成后 dict[] 甚至是字符串数组吗?

        char c, r;
        while((c = fgetc(in)) != EOF){ 
            while((r = fgetc(in)) != '\n'){
                dict[n] = r;
                n++;

            }
            dict[n+1] = '[=10=]'; //is this necessary?
            stringcompare(word, dict);
        }

这是错误的。

  • fgetc()的return值应该存储到int,而不是char,尤其是要和EOF比较的时候。
  • 您可能忘记初始化 n
  • 您将错过每行的第一个字符,该字符存储到 c
  • 使用 dict[n] = '[=17=]'; 而不是 dict[n+1] = '[=18=]'; 因为 n 已经在循环中增加了。

可能的修复:

int c, r;
while((c = fgetc(in)) != EOF){ 
    ungetc(c, in); // push the read character back to the stream for reading by fgetc later
    n = 0;
    // add check for EOF and buffer overrun for safety
    while((r = fgetc(in)) != '\n' && r != EOF && n + 1 < sizeof(dict) / sizeof(dict[0])){
        dict[n] = r;
        n++;

    }
    dict[n] = '[=10=]'; //this is necessary
    stringcompare(word, dict);
}