C语言问题求教,有5个学生,每个学生有3门课的成绩,从键盘输入以下数据(包括学号、姓名、语文,数学 100
C语言问题求教,有5个学生,每个学生有3门课的成绩,从键盘输入以下数据(包括学号、姓名、语文,数学,英语成绩)(按学号升序),将这些写入二进制文件stududent.da...
C语言问题求教,有5个学生,每个学生有3门课的成绩,从键盘输入以下数据(包括学号、姓名、语文,数学,英语成绩)(按学号升序),将这些写入二进制文件stududent.dat中。插入另外一个学生的信息。要求将该生插入到按学号排序的合适位置,然后将所有内容写到另外一个二进制文件stud1.dat中,并输出stud1.dat文件内容,不允许使用数组!高分求大神帮忙写代码,最好能顺便解释一下,急!!
展开
1个回答
展开全部
#include <stdio.h>
#include <stdlib.h>
#define MAXLENGTH 100
typedef struct student{
int number;
char name[MAXLENGTH];
double chinese, math, english;
struct student *next;
}student;
int main()
{
student *head, *tail, *node, *loc, *prev;
FILE *fout, *fin;
int i;
head = tail = NULL;
for (i = 0; i < 5; i++) //输入信息,建立链表
{
node = malloc(sizeof(student));
node->next = NULL;
printf("输入学号、姓名、语文、数学、英语成绩:\n");
scanf("%d %s %lf %lf %lf", &node->number, node->name,
&node->chinese, &node->math, &node->english);
if (head == NULL)
head = tail = node;
else //将新结点接到链表尾部
{
tail->next = node;
tail = node;
}
}
fout = fopen("stu.dat", "wb");
node = head;
while (node != NULL)
{
fwrite(node, sizeof(student), 1, fout);
node = node->next;
}
fclose(fout);
node = malloc(sizeof(student));
printf("输入要添加的学生学号、姓名、语文、数学、英语成绩:");
scanf("%d %s %lf %lf %lf", &node->number, node->name,
&node->chinese, &node->math, &node->english);
loc = head;
prev = NULL; //要插入位置的前趋
while (loc != NULL && loc->number < node->number) //寻找插入位置
{
prev = loc;
loc = loc->next;
}
if (prev == NULL) //插入到链表头
{
node->next = head;
head = node;
}
else
{
node->next = loc;
prev->next = node;
}
fout = fopen("stu1.dat", "wb"); //保存到stu1.dat
node = head;
while (node != NULL)
{
fwrite(node, sizeof(student), 1, fout);
node = node->next;
}
fclose(fout);
node = malloc(sizeof(student));
fin = fopen("stu1.dat", "rb");
fread(node, sizeof(student), 1, fin);
printf("学号:%d 姓名:%s 语文:%lf 数学:%lf 英语:%lf\n",
node->number, node->name, node->chinese, node->math, node->english);
while (node->next != NULL)
{
fread(node, sizeof(student), 1, fin);
printf("学号:%d 姓名:%s 语文:%lf 数学:%lf 英语:%lf\n",
node->number, node->name, node->chinese, node->math, node->english);
}
fclose(fin);
free(node); //回收内存
while (head != NULL)
{
node = head->next;
free(head);
head = node;
}
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询