I have a code which uses ungetc,and fefo function but i noticed that fefo is not checking for EOF below is my code
#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);
}
input is :
hello !world
outout if EOF is not chcked explicitly
hello @world
hello @world // Bad its repeat
output when EOF is checked explicitly
hello @world // Good
Why do i need to check for EOF and break when fefo does ?
If I understand correctly, you are reading from a file into a buffer and substituting
'@'for'!'when it occurs. Each of the comments above have provided you the reason, and a link to, why reading characters in awhileloop and testing withfeofis bad.Putting the comments together, and cleaning up the logic a bit, the following shows a standard way to accomplish this task. I have left your code commented inline to make the changes more apparent. Take a look and drop a comment if you have questions.:
Output