This can be done easily with fscanf :
#include <stdio.h> int main() { FILE* f = fopen("test.txt", "r"); int number = 0; int sum = 0; /* the sum of numbers in the file */ while( fscanf(f, "%d,", &number) > 0 ) // parse %d followed by ',' { sum += number; // instead of sum you could put your numbers in an array } fclose(f); }
@pmg: Of course, why not. I just, if it is hw, then it is bad to give a complete solution :)
#include <stdio.h> int main() { FILE* f = fopen("test.txt", "r"); int n = 0, i = 0; int numbers[5]; // assuming there are only 5 numbers in the file while( fscanf(f, "%d,", &n) > 0 ) // parse %d followed by ',' { numbers[i++] = n; } fclose(f); }
source share