How the end-of-file loop is made

3

Type, I know that the function feof () returns 0 if it did not find an end of file and that it requires 1 parameter, which is the variable_pile_pile_FILE pointer, so far so good.

If I do the while so it works like neither of the below but I do not understand how.

while(!feof(ponteiro_pra_variavel_tipo_FILE)) {
}

Is not that right to test like this?

while(feof(ponteiro_pra_variavel_tipo_FILE) == 0){
}

How does he know through !feof(ponteiro_pra_variavel_tipo_FILE) , that the function is returning 0 ?

    
asked by anonymous 19.06.2015 / 16:48

3 answers

3
What happens is that since C does not have the Boolean type, it interprets the integer variables to evaluate an expression, zero being false and non-zero being true, just as we are accustomed to using. Therefore there is no need to use feof(ponteiro_pra_variavel_tipo_FILE) == 0) because the expression itself already returns an integer value that is sufficient for the evaluation of while .

For clarification in this case, the function feof returns 0 when there is still a file to be processed, so both of the expressions you cited as an example have the same definition. The while will be repeated while the expression is true (the file is not finished).

    
19.06.2015 / 16:54
2

The feof function tells you if some file reading function has already tried to read some input and could not because of the end of the file. It does not say whether a read function will read the next entry.

What you should do is read the return value from your read functions and see if the read failed due to the end of the file. For example, the getchar and scanf functions return EOF when there are no characters to be read. Some examples of this in use:

int c;
while(c = getchar(), c != EOF){
    ...
}

int nr;
int blah;
while(EOF != scanf("%d", &blah)){
    ...
}

Returning to your question, it has to do with the fact that "true or false" is represented with integers in C. Try to make some printfs to get an idea:

printf("%d\n", (5 == 5));
printf("%d\n", (5 == 6));
printf("%d\n", !(5 == 6));
printf("%d\n", !3);

And the result is that C !x and x != 0 are equivalent.

    
19.06.2015 / 18:46
0

As the colleague above put it: C interprets directly, since, by default, it has this automatic "== 0",

I think that in very general lines can be compared to the case of

for (x=0;x<MAX;x++)
   o que executar

instead of

x=o;
while (x<MAX){
execução do código;
x=x+1;
}

Everything to save a few lines and the code becomes leaner and easier to assimilate. At least I see it that way.

Embrace

    
19.06.2015 / 18:10