【问题标题】:C program not reading from fileC程序不从文件中读取
【发布时间】:2015-10-17 19:58:43
【问题描述】:

我是 C 和文件处理的新手,我正在尝试打印文件的内容。如果这很重要,我正在使用 Code::Blocks。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
    char c;
    FILE *f;
    f = fopen("filename.txt", "rt");

    while((c=fgetc(f))!=EOF){
        printf("%c", c);
    }
    fclose(f);
    return 0;
}

【问题讨论】:

  • 好的,有什么问题?
  • if (f==NULL) ... // error handling
  • fgetc 的结果分配给char 是错误的。 EOF 不是 char
  • 请将char c; 更改为int c;,因为这是fgetc() 返回的类型。值EOF 必须与数据值0xFF 区分开来。使用printf("%c", c); 仍然是完全可以接受的,因为用作printf 的参数的char 无论如何都会提升为int
  • @WeatherVane 我会试试的。谢谢。

标签: c file file-handling


【解决方案1】:

关于未定义行为的简要说明:如果我们建议它崩溃,那么我们将定义它崩溃...我们不能这样做,因为它是 未定义的。我们只能说,未定义的行为是不可移植的,可能是不可取的,当然应该避免。


根据the fopen manual,打开文件有六种标准模式,"rt"不是其中之一。

我引用了列出这六种标准模式的部分。请注意重点(我的),指出如果您选择的不是这些标准模式之一,则行为未定义。

mode 参数指向一个字符串。如果字符串是以下之一,则应以指示的模式打开文件。 否则,行为未定义。

rrb

Open file for reading.

wwb

Truncate to zero length or create file for writing.

aab

Append; open or create file for writing at end-of-file.

r+rb+r+b

Open file for update (reading and writing).

w+wb+w+b

Truncate to zero length or create file for update.

a+ab+a+b

Append; open or create file for update, writing at end-of-file. 

好的,考虑到这一点,您可能打算使用"r" 模式。在fopen之后,您需要确保文件成功打开,正如其他人在cmets中提到的那样。可能会发生许多错误,我相信您可以推断出...您的错误处理可能看起来像这样:

f = fopen("filename.txt", "r");
if (f == NULL) {
    puts("Error opening filename.txt");
    return EXIT_FAILURE;
}

其他人也评论了fgetc的返回类型;它不会返回 char。它返回一个 int,这是有充分理由的。大多数情况下,它会成功返回(通常)256 个字符值之一,作为 unsigned char 值转换为 int。但是,有时您会得到 否定 intEOF。这是一个int 值,而不是字符值。 fgetc 返回的唯一字符值是正数。

因此您还应该对fgetc 执行错误处理,如下所示:

int c = getchar();
if (c == EOF) {
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多