fprintf 的格式规则与 printf 相同,但第一个参数是目标文件流。它返回成功写入的字符数,失败时返回负值。打开、检查、写入、关闭应形成完整流程。
#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;
}用 fscanf 读取结构化文本
fscanf 从文件流按格式转换数据,返回成功赋值的字段数。循环条件应检查期望字段数,而不是只与 EOF 比较。请复制下面的示例,在程序的当前工作目录中自行创建 scores.txt;每行包含一个无空格姓名和一个整数分数:
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 限制最多写入 31 个字符,并为结尾的 \0 留出空间。fscanf 的 %s 遇到空白就停止,因此不适合读取包含空格的整行。
知识测验
题目
fprintf(fp, ...) 与 printf(...) 的主要区别是什么?
知识测验
题目
读取“Grace 95”时,为什么检查 fscanf(...) == 2?
动手练习
写出一张订单摘要
创建 order.txt,用一次 fprintf 写入 item=Notebook quantity=3 total=29.97 和换行。检查 fopen、fprintf、fclose 的结果;任何一步失败都返回 1。
- 以写入模式打开 order.txt 并检查文件指针。
- 使用 fprintf 按指定格式写入一条订单记录。
- 检查 fprintf 是否失败,再检查 fclose 返回值。
动手练习
计算分数平均值
复制本节给出的文本并自行创建 scores.txt。用 fscanf(fp, "%31s%d", ...) 读取所有有效记录,统计数量和总分,最后输出一位小数的平均值;若没有有效记录则输出 no data。
- 检查 fopen 是否成功。
- 当 fscanf 成功赋值两个字段时累加分数并计数。
- 处理 count == 0,否则以一位小数输出平均值,并检查 fclose。