C/Read file
Expert: Narendra - 10/4/2004
Question-------------------------
Dear Sir,
I have try the following but the code keep on continuos looping and it only display 0 to 5, 6 to 9 not appearĄ.please help, thanksĄ
#include <stdio.h>
int main()
{
FILE *f;
int s[10],i=0, sum=0;
f=fopen("num.txt","r");
if (!f)
return 1;
while (!feof(f)){
sum=sum + s[i];
printf("%d",s);
i++;
}
fclose(f);
return 0;
}
num.txt content:
0
1
2
3
4
5
6
7
8
9
Followup To
Question -
Dear sir,
can you tell me how to Read a number field in a sequential file so that i can sum up this number in C language? Thanks..
Answer -
Read the file using fread() (If your file is binary) or fscanf() (If your file is ascii).
If you have many consecutive numbers, then read them in a loop.
Read them to a variable num.
Go on adding them to another variable sum like this:
sum = sum + num;
At the end sum will have the sum of all the numbers.
-ssnkumar
AnswerHere is the corrected code:
#include <stdio.h>
int main()
{
FILE *f;
int s[10], i = 0, sum = 0;
f=fopen("num.txt","r");
if (!f) return 1;
while (fscanf(f, "%d", &(s[i])) > 0)
{
sum = sum + s[i];
printf("%d\n", s[i]);
i++;
}
printf("SUM = %d\n", sum);
fclose(f);
return 0;
}