I'm trying to read each character from a file and print it to the screen using getc and putc alone. Here's my code,
FILE *fp = fopen("new.txt","r+");
rewind(fp);
while( feof(fp) == 0 )
{
putc( getc(fp) , stdout);
}
When ever I execute this, it runs into an infinite loop. I can't understand how this happens when the file is only a few lines long.
Newbie.
Looping while feof
returns zero is almost never correct.
Instead you might want to read from the input and check that the input function didn't fail in one expression:
int ch;
while ((ch = getc(fp)) != EOF)
putc(ch, stdout);
This reads a character using getc
, checks that the reading was successful by comparing the character against EOF
, and if it's not EOF
then continue the loop.
Besides, there's no use in calling rewind
immediately after opening the file, the file is already "rewound".