getc和fscanf之间的区别 [英] difference between getc and fscanf
问题描述
为什么以下代码能正常工作:
why does the following code work fine:
#include<stdio.h>
int main()
{
FILE *fp=fopen("input.txt","r+");
char c;
while((c=getc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
return 0;
}
但是此代码给出了错误分段错误,核心已转储":
but this code gives an error 'segmentation fault, core dumped':
#include<stdio.h>
int main()
{
FILE *fp=fopen("input.txt","r+");
char c;
while((c=fscanf(fp,"%c",&c))!=EOF)
{
printf("%c",c);
}
fclose(fp);
return 0;
}
input.txt包含空格分隔的字符列表,例如:a b c d e f
input.txt contains a space separated list of characters like: a b c d e f
推荐答案
这将无法按您期望的方式工作:
This will not work the way you expect:
while((c=fscanf(fp,"%c",&c))!=EOF)
getc()
返回读取的字符,可以是EOF
,但是fscanf()
返回分配的输入项数,如果在进行任何转换之前发生故障,则返回EOF
.
getc()
returns the character read, which can be EOF
, but fscanf()
returns the number of input items assigned, or EOF
if there was a failure before any conversion took place.
您不能将此返回值分配给c
,因为该返回值不是读取的字符(然后您尝试稍后打印).
You can't assign this return value to c
, because the return value is not the character read (which you then try to print later).
您应该尝试以下操作:
while(fscanf(fp,"%c",&c) == 1)
或者:
while(fscanf(fp,"%c",&c) != EOF)
这相当于说只要有一个要读的字符..."
Which is equivalent to saying "As long as there is a character to read..."
此外,在第一种情况(使用getc()
的代码)中,c
应该为int-如果目标平台使用无符号字符,则可以有一个无限循环,因为c
将始终转换为一个正整数(同样,仅在具有未签名字符的平台中),因此永远不会等于EOF
.如果查看getc()
和putc()
的手册页(以及其他处理字符的功能),您会发现它们收到的是int
,而不是char
.
Also, in the first case (the code where you use getc()
), c
should be int - you can have an infinite loop if the target platform uses unsigned chars, because c
will always be converted to a positive int (again, only in platforms with unsigned chars), and thus will never be equal to EOF
. If you check the manpages for getc()
and putc()
(and other functions that deal with a character), you will see that they receive int
, not char
.
这篇关于getc和fscanf之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!