8.2 Structured File I/O
When a text file has a regular structure, you can write and read fields with format strings. The file versions of printf() and scanf() are fprintf() and fscanf().
fprintf(file_pointer, "format", values...);
fscanf(file_pointer, "format", addresses...);fprintf() writes formatted text to a file stream. The first argument is the FILE *.
FILE *fp = fopen("scores.txt", "w");
fprintf(fp, "Ada %d\n", 96);
fprintf(fp, "Bob %d\n", 88);
fprintf(fp, "Cora %d\n", 91);
fclose(fp);That creates a simple structured text file:
Ada 96
Bob 88
Cora 91fscanf() reads fields from a file stream. It returns the number of fields successfully parsed, so the loop condition should check that number.
FILE *fp = fopen("scores.txt", "r");
char name[32];
int score;
int total = 0;
int count = 0;
while (fscanf(fp, "%31s %d", name, &score) == 2) {
total += score;
count++;
}
fclose(fp);
printf("average = %.1f\n", total / (double) count);Use width limits such as %31s when reading strings into arrays. The width leaves room for the ending \0.
fscanf() is best for predictable files where every record follows the same shape. If the file may contain blank lines, comments, missing fields, or free-form text, read a whole line first with fgets() and then decide how to parse it.