我是 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
orrb
Open file for reading.
w
orwb
Truncate to zero length or create file for writing.
a
orab
Append; open or create file for writing at end-of-file.
r+
orrb+
orr+b
Open file for update (reading and writing).
w+
orwb+
orw+b
Truncate to zero length or create file for update.
a+
orab+
ora+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/