#include <stdio.h>

/* Demo 06：文件操作（运行后当前目录会生成 students.txt） */

typedef struct
{
    int id;
    char name[20];
    float score;
} Student;

int main()
{
    // 1. fprintf 写入
    FILE *fp = fopen("students.txt", "w");
    if (fp == NULL)
    {
        perror("文件打开失败");
        return -1;
    }

    Student stus[3] = {{1, "张三", 92.5}, {2, "李四", 88.0}, {3, "王五", 78.5}};
    for (int i = 0; i < 3; i++)
        fprintf(fp, "%d %s %.1f\n", stus[i].id, stus[i].name, stus[i].score);
    fclose(fp);
    printf("已写入 students.txt\n");

    // 2. fscanf 逐行读取
    fp = fopen("students.txt", "r");
    if (fp == NULL)
        return -1;

    Student stu;
    printf("--- 读取内容 ---\n");
    while (fscanf(fp, "%d %s %f", &stu.id, stu.name, &stu.score) != EOF)
        printf("%d %s %.1f\n", stu.id, stu.name, stu.score);
    fclose(fp);

    // 3. 求文件大小
    fp = fopen("students.txt", "r");
    fseek(fp, 0, SEEK_END);
    printf("文件大小：%ld 字节\n", ftell(fp));
    fclose(fp);

    return 0;
}
