# Thread: How To Sum undetermined number from a txt File in C

1. ## How To Sum undetermined number from a txt File in C

Hi
i have problem with using TXT file in C. Actually, i have a txt file stored in C:\\ . It contains numbers. i don't know how many number i have in this TXT File. i want a program which opens the file and sum the number. would you help me with that ?

Thank You

2. If you just need the sum, then it seems quite trivial: read one number at a time and add it to the current sum. After you are done reading the entire file, you would have the sum of the numbers, regardless of how many there were (assuming that the integer type you chose has a range large enough to store this sum).

3. Originally Posted by laserlight
If you just need the sum, then it seems quite trivial: read one number at a time and add it to the current sum. After you are done reading the entire file, you would have the sum of the numbers, regardless of how many there were (assuming that the integer type you chose has a range large enough to store this sum).
Actually, i wrote this code for reading 10 numbers from a txt file and calculates the AVG of the numbers. Now, i want to do the same for n (dont know how many numbers we have) . how can i change the code ?
thank you

Code:
```#include <stdio.h>
#include <conio.h>

int main()
{

FILE *fp;
int i;
int s=0;
int a;

fp=fopen("D:\\a.txt", "r+");
if (fp!=0)
{
for(i=0; i<=9; i++)
{
fscanf(fp,"%d",&a);
s+=a;
}
printf("%d", s/10);
int mkji = fclose(fp);
}
else
printf("FILE CANNOT BE OPEN");

getch();
return 0;

}```

4. Hints:
1. You can count the number of numbers while reading.
2. Make use of the fact that fscanf(fp,"%d",&a) == 1, then the read was successful.
3. Use better variable names.