C编程中的文件处理:以下两个代码之间有什么区别? [英] File handling in C programming: What is the difference between below two codes?
问题描述
代码1:
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("1.txt","r");
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
fclose(fp);
}
代码2:
#include<stdio.h>
void main()
{
FILE *fp;
int ch;
fp=fopen("1.txt","r");
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
fclose(fp);
}
在CODE#1中,变量ch在以下位置以字符数据类型声明CODE#2是在整数数据类型下声明的,我的问题是两个代码的输出为何相同?我们如何比较字符(存储在CODE#1的ch变量中)和整数值(由EOF返回)?又如何将整数值存储在ch变量(整数数据类型)中并在CODE#2中打印?
Here in CODE #1 variable ch is declared under character data type while in CODE #2 it's declared under integer data type, My question is how come the output of both codes be same? How can we compare character(stored in ch variable in CODE #1) with integer value(returned by EOF)? And how can integer value stored in ch variable(of interger data type) and printed in CODE #2?
推荐答案
CODE#1显然是错误的,这是程序员常见的错误.fgetc精确地返回一个int,以便可以将该值与EOF进行比较.
CODE#1 is obviously wrong and it is a common mistake done by programmers. fgetc returns an int precisely so that the value can be compared with EOF.
EOF扩展为整数常数,它是与实现相关的负值,但最常见的是-1.因此,将fgetc的返回值分配给char时,它将被截断为255,这是有效的char值.这就是为什么fgetc具有int的返回类型,并且从fgetc返回的值永远不能分配给char的原因.
EOF expands to an integer constant value and it is an implementation dependent negative value, but, most commonly it will be -1. So, when the return value of fgetc is assigned to char it gets truncated to 255 which is a valid char value. This is the reason why fgetc has the return type of int and value returned from fgetc should never be assigned to a char.
整数值如何存储在ch变量(整数数据类型)中并打印在CODE#2中?
fgetc的手册页明确指出
The man page of fgetc clearly states
fgetc()从流中读取下一个字符,并以无符号字符的形式将其返回给int,或者在文件或错误结束时返回EOF.
因此,只要返回的值不是EOF,就将其类型转换为char以进行打印就可以了.
So, typecasting it to char to print it is fine as long as the returned value is not EOF.
这篇关于C编程中的文件处理:以下两个代码之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!