fBfX
fBfX

Reputation: 5

Can't reach EOF with fscanf loop

Helo, as I continue with my HW project, i am stucked in reading EOF, given this loop, it's stucked forever and obviously, input never gets value of EOF, what am I doing wrong?

int main ()
{
FILE *ffil;
char input;
ffil=fopen("a.csv","r");
printf("error0");
do
{
    fscanf("%c",&input);
}while(input!=EOF);
fclose(ffil);
return 0;
}

Upvotes: 0

Views: 7830

Answers (1)

Joe Z
Joe Z

Reputation: 17936

scanf doesn't work that way. Also, EOF does not fit in a char. If you want to read character by character until EOF, do it the idiomatic way:

int input;  /* int, not char! */

while ( (input = getchar()) != EOF )
{
    /* do stuff with 'input' here. */
}

If you really want to use scanf, you can. It returns the number of values successfully converted, so you could use that instead of testing for EOF:

char input;  /* char, not int! */

while ( scanf("%c", &input) == 1 )  /* loop while scanf succeeds */
{
    /* do stuff with 'input' here */
}

Both of those read from stdin, but it appears your test really wants to read from ffil. If that's the case (it wasn't clear from your question), modify the above examples as follows:

int input;  /* int, not char! */

while ( (input = fgetc(ffil)) != EOF )
{
    /* do stuff with 'input' here. */
}

or

char input;  /* char, not int! */

while ( fscanf(ffil, "%c", &input) == 1 )  /* loop while scanf succeeds */
{
    /* do stuff with 'input' here */
}

Upvotes: 3

Related Questions