一条完整的流水线
(本条路线统一用 gcc -std=c11 -O0 -Wall 编译)写文件 → 读回来 → 存进堆 → 算 → 全部还回去:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int got = 0, gave = 0; /* l1_lang_05 那块仪表盘接着用 */
int main(void) {
FILE *f = tmpfile();
if (f == NULL) { printf("建不出\n"); return 1; }
const char *rows[4] = {"apple 3", "pear 5", "plum 2", "fig 4"};
for (int i = 0; i < 4; i++) fprintf(f, "%s\n", rows[i]);
rewind(f);
/* 边读边把每行存进堆上的一份副本 */
char **kept = malloc(4 * sizeof(char *));
got++;
int n = 0;
char name[32];
int qty, total = 0;
while (n < 4 && fscanf(f, "%31s %d", name, &qty) == 2) {
kept[n] = malloc(strlen(name) + 1);
got++;
strcpy(kept[n], name);
total += qty;
n++;
}
fclose(f);
int longest = 0;
for (int i = 0; i < n; i++)
if ((int)strlen(kept[i]) > longest) longest = (int)strlen(kept[i]);
for (int i = 0; i < n; i++) { free(kept[i]); gave++; }
free(kept); gave++;
printf("%d/%d/%d/%d\n", n, total, longest, got - gave);
return 0;
}
全部评论