#include <string.h>
#include <stdlib.h>
int N;/////總人數
struct student
{
char name[20];////姓名
int math[2];////math[0]課程是否被選,math[1]記錄成績
int physical[2];
int computer[2];
int english[2];
};
void initelse(struct student *p)
{
printf("\n輸入數學成績,若該生未選輸入0\t");
scanf("%d", &p->math[0]);
if(p->math[0])
{
printf("\n請輸入數學成績\t");
scanf("%d", &p->math[1]);
}
else
p->math[1]=0;
printf("\n輸入物理成績,若該生未選輸入0\t");
scanf("%d", &p->physical[0]);
if(p->math[0])
{
printf("\n請輸入物理成績\t");
scanf("%d", &p->physical[1]);
}
else
p->physical[1]=0;
printf("\n輸入計算機成績,若該生未選輸入0\t");
scanf("%d", &p->computer[0]);
if(p->math[0])
{
printf("\n請輸入計算機成績\t");
scanf("%d", &p->computer[1]);
}
else
p->computer[1]=0;
printf("\n輸入英語成績,若該生未選輸入0\t");
scanf("%d", &p->english[0]);
if(p->math[0])
{
printf("\n請輸入英語成績\t");
scanf("%d", &p->english[1]);
}
else
p->english[1]=0;
};
void init(struct student *p)
{
printf("請輸入學生姓名\t");
scanf("%s", p->name);
initelse(p);
};
////////////////////////////初始化函數
void modify(struct student* student)
{
char temp[20];
int i;
printf("\n----------------------------\n");
printf("請輸入要修改的學生的姓名\t");
scanf("%s", temp);
printf("\n");
for(i=0;i<N;i++)
{
if(strcmp(student[i].name, temp)==0)
initelse(&student[i]);
else
printf("沒有這個學生\n");
}
};////////////////////////修改函數
void displayall(struct student *student)
{
int i;
for(i=0;i<N;i++)
{
printf("姓名: %s\n", student[i].name);
if(student[i].math[0])
printf("數學成績:%d\t", student[i].math[1]);
else
printf("該生沒有選擇數學!\t");
if(student[i].physical[0])
printf("物理成績:%d\n", student[i].physical[1]);
else
printf("該生沒有選擇物理!\t");
if(student[i].computer[0])
printf("計算機成績:%d\t", student[i].computer[1]);
else
printf("該生沒有選擇計算機\t");
if(student[i].english[0])
printf("英語成績:%d\t", student[i].english[1]);
else
printf("該生沒有選擇英語\n");
}
};/////////////輸出學生信息
int main()
{
int i;
char yesorno;
FILE *stream;
struct student *student ;
printf("請輸入學生的總人數:\t");
scanf("%d", &N);
student=(struct student*)malloc(sizeof(student)*N);
for(i=0;i<N;i++)
init(&student[i]);
printf("數據初始化完成!\n");
displayall(student);
printf("是否要修改?y修改,n不修改\t");
scanf("%c",&yesorno);
getchar();
while(yesorno=='y')
{
modify(student);
printf("修改下壹個輸入:y,其他任意鍵退出!\n");
scanf("%c", &yesorno);
getchar();
}
printf("按任意鍵開始寫入文件!\n");
getchar();
if((stream=fopen("a.dat", "w+"))==NULL)
{
perror("寫入文件失敗");
printf("\n按任意鍵退出\n");
getchar();
exit(1);
}
fwrite(&student, sizeof(student)*N, 1, stream);
printf("寫入成功\n");
//free(student);
exit(0);
}