Save some numbers to a file, and add them up from the file.
What to build
A program that writes a file and then reads it.
Requirements
- Write each input number to a file called
data.txt, one per line. - Close the file, open it again for reading, and add up the numbers from the file.
- Print the total.
Input
The first line has n. The second line has n whole numbers.
Output
One number.
Constraints
n is from 0 to 100. When n is 0, the second line is empty.
Example
Input:
3
1 2 3
Output:
6
Why it works
Reading until fscanf stops returning 1 works for any length of file, with no need to know the count in advance.
Examples
Example 1 · Input
3 1 2 3
Expected output
6
Example 2 · Input
0
Expected output
0
Hints
Hint 1
Open with "w", write each number, and close.
Hint 2
Open again with "r", and loop while fscanf returns 1.
Hint 3
Check both fopen calls.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
FILE *out = fopen("data.txt", "w");
if (out == NULL) return 1;
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
fprintf(out, "%d\n", x);
}
fclose(out);
FILE *in = fopen("data.txt", "r");
if (in == NULL) return 1;
int x, total = 0;
while (fscanf(in, "%d", &x) == 1) {
total += x;
}
fclose(in);
printf("%d\n", total);
return 0;
}