/* file stu_io.c, 程序 stu 的输入输出源程序文件 */
#include "utilities.h"
#include "stu.h"

static int check(double x) {
    return x >= 0.0 && x <= 100.0;
}

static int readrec(FILE* fp, StuRec *stp) {
    char s[256];

    if (fgets(s, 256, fp) == NULL) return EOF;
    if (sscanf(s, "%lu %s%lf%lf%lf", &stp->num, stp->name,
            &stp->mid, &stp->exe, &stp->final) == 5)
        if (check(stp->mid) && check(stp->exe) && check(stp->final)) {
            stp->score = (stp->mid*MIDDLE + stp->exe*EXECISE +
                          stp->final*FINAL) / 100;
            return 1;
        }

    return 0;
}

int readSRecs(FILE *fp, int limit, StuRec tb[]) {
    int i = 0, line = 1, n;
    double x;

    while (i < limit && (n = readrec(fp, &tb[i])) != EOF) {
        if (n == 0)
            printf("Data error, line %d\n", line);
        else ++i;

        ++line;
    }

    if (i == limit && !feof(fp)) { /* 还有数据 */
        printf("Too many data. Output is not correct.\n");
        return 0;
    }

    return i;
}

int printSRec(FILE *fp, int limit, StuRec tb[]) {
    int i;

    for (i = 0; i < limit; ++i) 
        fprintf(fp, "%-10lu%20s%6.1f%6.1f%6.1f%6.1f\n", tb[i].num,  
            tb[i].name, tb[i].mid, tb[i].exe, tb[i].final, tb[i].score);

    return 0;
}

