fprintf uses the same formatting rules as printf, but its first argument is the destination stream. It returns the number of characters written or a negative value on failure. Opening, checking, writing, and closing form one complete workflow.
#include <stdio.h>
int main(void) {
FILE *fp = fopen("report.txt", "w");
if (fp == NULL) {
fprintf(stderr, "Cannot open report.txt.\n");
return 1;
}
int count = 3;
double average = 91.5;
if (fprintf(fp, "count=%d average=%.1f\n", count, average) < 0) {
fclose(fp);
return 1;
}
if (fclose(fp) != 0) {
return 1;
}
return 0;
}Reading structured text with fscanf
fscanf converts input from a stream according to a format and returns the number of fields assigned. A loop should check the expected field count rather than merely comparing with EOF. Create scores.txt in the program's current working directory by copying this sample, which contains one whitespace-free name and one integer score per line:
Ada 91
Linus 88
Grace 95#include <stdio.h>
int main(void) {
FILE *fp = fopen("scores.txt", "r");
if (fp == NULL) {
fprintf(stderr, "Cannot open scores.txt.\n");
return 1;
}
char name[32];
int score;
while (fscanf(fp, "%31s%d", name, &score) == 2) {
printf("%-10s %d\n", name, score);
}
if (fclose(fp) != 0) {
return 1;
}
return 0;
}%31s writes at most 31 characters, leaving room for \0. The %s conversion stops at whitespace, so it is not suitable for a complete line containing spaces.
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Write an order summary
Create order.txt and use one fprintf call to write item=Notebook quantity=3 total=29.97 plus a newline. Check fopen, fprintf, and fclose; return 1 if any step fails.
- Open order.txt in write mode and validate the stream.
- Use fprintf to write one record in the required format.
- Check fprintf for failure and then check fclose.
Calculate the score average
Copy the text shown in this lesson to create scores.txt. Use fscanf(fp, "%31s%d", ...) to process every valid record, track count and total, and print the average to one decimal place. Print no data if there are no valid records.
- Check whether fopen succeeded.
- Accumulate while fscanf assigns both fields.
- Handle count == 0; otherwise print one decimal place and check fclose.