Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C程序不从文件中读取_C_File_File Handling - Fatal编程技术网

C程序不从文件中读取

C程序不从文件中读取,c,file,file-handling,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和文件处理,我正在尝试打印文件的内容。我正在使用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;
}
关于未定义行为的简要说明:如果我们建议它崩溃,那么我们将它定义为崩溃。。。我们不能这样做,因为它是未定义的。我们所能说的是,未定义的行为是不可移植的,可能是不受欢迎的,当然是要避免的

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

我引用了列出这六种标准模式的章节。请注意我的重点,指出如果您选择的不是这些标准模式中的一种,那么行为是未定义的

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

r或rb

w或wb

a或ab

r+或rb+或r+b

w+或wb+或w+b

a+或ab+或a+b

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

f = fopen("filename.txt", "r");
if (f == NULL) {
    puts("Error opening filename.txt");
    return EXIT_FAILURE;
}
其他人也评论了fgetc的回报类型;它不返回字符。它返回一个int,这是有充分理由的。大多数情况下,它会成功地返回典型的256个字符值中的一个,作为转换为int的正无符号字符值。但是,偶尔会得到负int值EOF。这是一个int值,不是字符值。fgetc返回的唯一字符值为正

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

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

好的,有什么问题吗?如果f==NULL…//错误处理将fgetc的结果分配给字符是错误的。EOF不是字符。请更改字符c;到INTC;因为这是fgetc返回的类型。值EOF必须与数据值0xFF区分开来。使用printf%c,c仍然是完全可以接受的;因为用作printf参数的char被提升为int。@WeatherVane我会试试。谢谢
Append; open or create file for writing at end-of-file.
Open file for update (reading and writing).
Truncate to zero length or create file for update.
Append; open or create file for update, writing at end-of-file. 
f = fopen("filename.txt", "r");
if (f == NULL) {
    puts("Error opening filename.txt");
    return EXIT_FAILURE;
}
int c = getchar();
if (c == EOF) {
    return 0;
}