c语言 结构体与文件

c语言 结构体与文件,第1张

#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

}

比如三个.c文件一个.h文件

c      2.c     3.c      4.h

这三个头文件都引用4.h include<4.h>

4.h中定义一个结构类型struct test{}  

1.c中定义一个该结构体类型的全局变量struct test mode

4.h中extern struct test mode

其他.c文件就可以直接使用这个结构体变量了,并且是共用的

引用结构体有引用类型,和引用全局变量两种方式。

1 引用类型。

需要将结构体定义与头文件中(.h文件),然后在需要引用类型的源文件(.c)中,均引用该头文件,即可使用该类型。

2 引用全局变量。

要引用全局变量,需要先引用类型,之后在一个源文件中定义全局变量,在其它源文件中声明该全局变量,即可使用。

比如结构体为struct test, 定义全局变量为

struct test glabol_test

在其它文件中,只需要

extern struct test globol_test

即可在对应文件声明所在行之下进行调用。

PS:该声明部分,也可以写在定义结构体的头文件中。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11459251.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-16
下一篇 2023-05-16

发表评论

登录后才能评论

评论列表(0条)

保存