Example 1 — Save and load name/score records
Compute an average after reading them back.
#include <stdio.h>
int main(void) {
FILE *fp = fopen("scores.txt", "w");
if (!fp) return 1;
fprintf(fp, "%s %d\n", "Ava", 90);
fprintf(fp, "%s %d\n", "Ben", 85);
fclose(fp);
char name[32];
int score, total = 0, count = 0;
fp = fopen("scores.txt", "r");
if (!fp) return 1;
while (fscanf(fp, "%31s %d", name, &score) == 2) {
printf("%s: %d\n", name, score);
total += score;
count++;
}
fclose(fp);
printf("Average: %.1f\n", (double)total / count);
return 0;
} How It Works
- Each record is one line: a name and a score.
fscanf(...) == 2stops at the end of the file or a malformed line.- (90 + 85) / 2 = 87.5.
