我有一个使用ungetc和fefo函数的代码,但我注意到fefo没有检查下面是我的代码
#include<stdio.h>
int main ()
{
FILE *fp;
int c;
char buffer [200];
fp = fopen("", "r");
if( fp == NULL )
{
perror("Error in opening file");
return(-1);
}
while(!feof(fp))
{
c = getc (fp);
if(c==EOF) // **why i need to check for EOF if fefo does?**
break;
/* replace ! with + */
if( c == '!' )
{
ungetc ('@', fp);
}
else
{
ungetc(c, fp);
}
fgets(buffer, 255, fp);
fputs(buffer, stdout);
}
return(0);
}
输入为:
hello !world
如果EOF未显式检查则输出
hello @world
hello @world // Bad its repeat
显式检查EOF时的输出
hello @world // Good
为什么我需要检查EOF和打破当fefo做?
如果我理解正确,您正在从文件中读取缓冲区并在发生'!'
时替换'@'
。上面的每个评论都为您提供了原因和链接,为什么在while
循环中读取字符并使用feof
测试是坏的。
将注释放在一起,并稍微清理一下逻辑,下面显示了完成此任务的标准方法。我留下了内联注释代码,以使更改更加明显。看一看,如果你有问题,留下评论:
#include <stdio.h>
#define MAXC 255
int main (int argc, char **argv) {
FILE *fp = NULL;
int c;
char input[MAXC];
char buffer[MAXC];
size_t idx = 0;
if (argc < 2) {
fprintf (stderr, "n error: insufficient input, filename required.n");
return 1;
}
if (!(fp = fopen (argv[1], "r"))) {
fprintf (stderr, "n error: file open failed '%s' (%p)n", argv[1], fp);
return 1;
}
while ( (c = getc (fp)) != EOF )
{
input[idx] = c;
if (c == '!') c = '@';
buffer[idx++] = c;
if (idx == MAXC) { /* normally realloc if buffer is allocated */
printf (" warning: maximum size of buffer reached (%d char)n", MAXC);
break;
}
// {
// ungetc ('@', fp);
// } else {
// ungetc (c, fp);
// }
// fgets (buffer, 255, fp);
// fputs (buffer, stdout);
}
fclose (fp);
input[idx] = buffer[idx] = 0;
// fputs (buffer, stdout);
printf ("n characters in input & buffer are:nn");
printf ("n original : %sn modified : %snn", input, buffer);
return 0;
}
$ ./bin/whyfeofbad dat/qbfox2.txt
characters in input & buffer are:
original : The quick! brown fox jumps over the lazy! dog. He never says "Hi!", he just saunters up and jumps!
modified : The quick@ brown fox jumps over the lazy@ dog. He never says "Hi@", he just saunters up and jumps@