#include<stdio.h> #include<iostream.h> #include<windows.h>
struct Student { int id; char name[30]; char sex; int score; }; void main() { FILE *fp; struct Student studentType[2],*p=studentType; int i; if((fp=fopen("d:\\thybare","wb"))==NULL) { printf("can not open file:\n"); exit(1); } for(i=0;i<2;i++) //如用指针 for(i=0;i<2;i++,p++) { printf("enter student id\n"); scanf("%d",&studentType[i].id); //为什么这里改成&p->id就 运行不行啊 fflush(stdin); printf("enter student name\n"); scanf("%s",studentType[i].name); //为什么这里改成p->name就 运行不行啊 fflush(stdin); printf("enter student sex\n"); scanf("%c",&studentType[i].sex); //为什么这里改成&p->sex就 运行不行啊 printf("enter student score\n"); scanf("%d",&studentType[i].score); ////为什么这里改成p->score就 运行不行啊 } if((fwrite(p,sizeof(struct Student),2,fp))!=2) { printf("can not write file:"); exit(1); } fclose(fp); if((fp=fopen("d:\\thybare","rb"))==NULL) { printf("can not open file:"); exit(1); } p=studentType; for(i=0;i<2;i++,p++) { if(fread(p,sizeof(struct Student),1,fp)==1) printf("%d\n%s\n%c\n%d\n",p->id,p->name,p->sex,p->score); else printf("can not read the file:"); } fclose(fp); }