Pregunta

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.

¿Fue útil?

Solución

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".

Otros consejos

use the following program for your answer.use fgetc() to get the character from file and use printf() function to print the character to screen.

#include<stdio.h>
#include<conio.h>
main()
{
    FILE *fp;
    char c;
    clrscr();
    fp=fopen("new.txt","r+");
    c=fgetc(fp);
    while(c!=EOF)
    {
        printf("%c",c);
        c=fgetc(fp);
    }
    getch();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top