Hello friends. I'm a beginner in C programming, and I have a question related to dealing with files. In the following piece of code, I'm reading two numbers from a file and saving both, together with their sum, in another file.
My question is: why is it that the following loop works?
Code:
fscanf(arq, "%d%d", &v1, &v2);
while(!feof(arq))
{
sum = v1 + v2;
FILE *fp = fopen("e79_resultado.txt", "a");
fprintf(fp, "%d\t%d\t%d\n", v1, v2, soma);
fclose(fp);
fscanf(arq, "%d%d", &v1, &v2);
}
whereas the loop below does not produce the expected result?
Code:
while(!feof(arq))
{
fscanf(arq, "%d%d", &v1, &v2);
sum = v1 + v2;
FILE *fp = fopen("e79_resultado.txt", "a");
fprintf(fp, "%d\t%d\t%d\n", v1, v2, soma);
fclose(fp);
}
Why do I have to read the information once outside the loop to make it work? Aren't they supposed to be the same thing?
Thanks in advance.