c语言 结构体与文件

c语言 结构体与文件设计一个学生结构体类型student,包括学生学号no,姓名name,成绩cj(三门课),求5个学生每个学生的平均成绩,并将原有的数据和计算出的平均分数存放到磁盘文件stud中

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define print_error(str) fprintf(stdout, "ERROR: %s\n", str)
#define NUM 5

typedef struct Score
{
    float a;
    float b;
    float c;
} Score;

typedef struct Student
{
    char  no[11];
    char  name[8];
    Score cj;
    float avg;
} Student;

void init_student(Student * st, int len)
{
    if (0 == st || 0 >= len)
    {
        print_error("student is NULL or LENGTH is zero");
        exit(-1);
    }

    printf("input no name cj[a, b, c]\n");
    for (int i = 0; i < len; ++i)
    {
        printf("%d--> ", i + 1);
        scanf("%s %s %f %f %f", st[i].no, st[i].name, &st[i].cj.a, &st[i].cj.b,
              &st[i].cj.c);
    }
}

void display(Student * st, int len)
{
    if (0 == st || 0 >= len)
    {
        print_error("student is NULL or LENGTH is zero");
        exit(-1);
    }

    for (int i = 0; i < len; ++i)
    {
        printf("%s %s %.1f %.1f %.1f %.1f\n", st[i].no, st[i].name, st[i].cj.a,
               st[i].cj.b, st[i].cj.c, st[i].avg);
    }
}

void calc_avg(Student * st, int len)
{
    if (0 == st || 0 >= len)
    {
        print_error("student is NULL or LENGTH is zero");
        exit(-1);
    }

    for (int i = 0; i < len; ++i)
    {
        st[i].avg = (st[i].cj.a + st[i].cj.b + st[i].cj.c) / 3.0;
    }
}

void save(Student * st, int len, const char * file_name)
{
    if (0 == st || 0 >= len || 0 == file_name)
    {
        print_error("student is NULL or LENGTH is zero or file error");
        exit(-1);
    }

    FILE * fp = fopen(file_name, "w+");
    if (fp)
    {
        char buf[255] = {0};

        for (int i = 0; i < len; ++i)
        {
            sprintf(buf, "%s %s %.1f %.1f %.1f %.1f\n", st[i].no, st[i].name,
                    st[i].cj.a, st[i].cj.b, st[i].cj.c, st[i].avg);
            fwrite(buf, strlen(buf), 1, fp);
            memset(buf, 0x00, sizeof(buf));
        }
        fclose(fp);
    }
}

int main(int argc, char *argv[])
{
    Student st[NUM];
    init_student(st, NUM);
    printf("-------------------\n");
    calc_avg(st, NUM);

    printf("-------------------\n");
    display(st, NUM);
    save(st, NUM, "d:\\stud");   // 文件名,按实际修改

    return 0;
}

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网