// ===== CodeLab: C 文件操作 =====
// 来源: https://aoerliang.dpdns.org/articles/c-file-io
// 以下代码片段按文章出现顺序拼接, 共 4 段

// ----- 片段 1 (c) -----
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("notes.txt", "w");
    if (fp == NULL) {
        printf("无法打开文件\n");
        return 1;
    }

    fprintf(fp, "Hello, C File!\n");
    fprintf(fp, "第 %d 行: 今天写了 %d 行代码\n", 2, 120);
    fputs("fputs 写的最后一行\n", fp);

    fclose(fp);
    printf("写入完成\n");
    return 0;
}

// ----- 片段 2 (c) -----
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("notes.txt", "r");
    if (fp == NULL) {
        printf("文件不存在\n");
        return 1;
    }

    char line[100];
    while (fgets(line, sizeof(line), fp) != NULL) {
        printf("读到: %s", line);   // fgets 会保留换行符
    }
    fclose(fp);
    return 0;
}

// ----- 片段 3 (c) -----
#include <stdio.h>

struct Record {
    int id;
    double value;
};

int main(void) {
    struct Record recs[2] = {{1, 3.14}, {2, 2.71}};

    FILE *fp = fopen("data.bin", "wb");
    fwrite(recs, sizeof(struct Record), 2, fp);
    fclose(fp);

    struct Record readback[2];
    fp = fopen("data.bin", "rb");
    fread(readback, sizeof(struct Record), 2, fp);
    fclose(fp);

    printf("读回: id=%d value=%.2f\n", readback[1].id, readback[1].value);
    return 0;
}

// ----- 片段 4 (c) -----
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("scores.txt", "r");
    if (fp == NULL) {
        perror("打开失败");        // 打印具体错误原因
        return 1;
    }

    int score, count = 0, sum = 0;
    while (fscanf(fp, "%d", &score) == 1) {  // 读到才继续
        sum += score;
        count++;
    }
    if (feof(fp)) {
        printf("平均 %.1f\n", sum / (double)count);
    }
    fclose(fp);
    return 0;
}
