Files
Parse Records
fscanf can parse simple structured records from a file.
Parse Records
parse_records.c
#include <stdio.h>
int main(void) {
int bonus = ;
FILE *file = fopen("parse_records_demo.txt", "w+");
if (file == 0) {
return 1;
}
fprintf(file, "A %d\n", 10 + bonus);
fprintf(file, "B %d\n", 20);
rewind(file);
char name = 0;
int score = 0;
int total = 0;
while (fscanf(file, " %c %d", &name, &score) == 2) {
total += score;
}
fclose(file);
remove("parse_records_demo.txt");
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int bonus = ;
FILE *file = fopen("parse_records_demo.txt", "w+");
if (file == 0) {
return 1;
}
fprintf(file, "A %d\n", 10 + bonus);
fprintf(file, "B %d\n", 20);
rewind(file);
char name = 0;
int score = 0;
int total = 0;
while (fscanf(file, " %c %d", &name, &score) == 2) {
total += score;
}
fclose(file);
remove("parse_records_demo.txt");
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int bonus = ;
FILE *file = fopen("parse_records_demo.txt", "w+");
if (file == 0) {
return 1;
}
fprintf(file, "A %d\n", 10 + bonus);
fprintf(file, "B %d\n", 20);
rewind(file);
char name = 0;
int score = 0;
int total = 0;
while (fscanf(file, " %c %d", &name, &score) == 2) {
total += score;
}
fclose(file);
remove("parse_records_demo.txt");
printf("total=%d\n", total);
return 0;
}
record fields
Each successful scan fills the fields for one record.
running total
The loop accumulates one field from each parsed record.