C程序不读取文件

标签 c file file-handling

我是 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;
}

最佳答案

关于未定义行为的快速说明:如果我们建议它崩溃,那么我们会将其定义为崩溃......我们不能这样做,因为它是未定义的。我们只能说,未定义的行为是不可移植的,可能是不可取的,并且肯定要避免。

<小时/>

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

我引用了列出这六种标准模式的部分。请注意强调(我的),指出如果您选择这些标准模式之一以外的其他模式,则行为未定义。

The mode argument points to a string. If the string is one of the following, the file shall be opened in the indicated mode. Otherwise, the behavior is undefined.

r or rb

Open file for reading.

w or wb

Truncate to zero length or create file for writing.

a or ab

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

r+ or rb+ or r+b

Open file for update (reading and writing).

w+ or wb+ or w+b

Truncate to zero length or create file for update.

a+ or ab+ or a+b

Append; open or create file for update, writing at end-of-file. 
<小时/>

好的,考虑到这一点,您可能打算使用 "r"模式。正在关注fopen ,您需要确保文件打开成功,正如其他人在评论中提到的那样。可能会发生很多错误,我相信您可以推断出...您的错误处理可能应该如下所示:

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

其他人也评论了 fgetc 的返回类型;它不会返回 char 。它返回一个 int ,并且有充分的理由。大多数时候,它会成功返回(通常)256 个字符值之一,作为 unsigned char值转换为int 。不过,有时您会得到负面 int值,EOF 。这是一个int值,而不是字符值。 唯一字符值fgetc返回率为正。

因此您还应该对 fgetc 执行错误处理,像这样:

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

关于C程序不读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33190981/

相关文章:

c - 标准 C 库和系统调用如何协同工作?

Python读取目录中的文件并连接

c - 如何在 C 中一次性提供第一个输入文件的输出作为第二个输入文件?

c++ - 如何在文本文件中找到一行并替换它?

c++ - powerpc Maliit 框架交叉编译问题

c - 参数数量与原型(prototype)不匹配等

c - 在 c 中使用 sscanf 的正则表达式忽略空格

我可以获得内存中已有数据支持的 FILE* 吗?

php - is_file 或 file_exists 在 PHP

java - 如何从 txt 文件中读取 Java 中的 2 个特定列?