C语言文件操作中的问题,关于fread和fwrite
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct student)
struct student
{
long int NO;
char name[30];
float achievement[6];
float aver;
float sum;
struct student*next;
};
struct student*input(int a,int b)
{
int i=0,r;
struct student*p1,*p2,*head;
head=p1=p2=(struct student*)malloc(LEN);
while(i<a)
{
i=i+1;
p1->sum=0;
printf("请输入学号:姓名:\n");
scanf("%d%s",&p1->NO,&p1->name);
for(r=0;r<b;r++)
{
printf("请输入第%d门成绩:\n",r+1);
scanf("%f",&p1->achievement[r]);
p1->sum=p1->sum+p1->achievement[r];
}
p1->aver=p1->sum/b;
if(i==1)
{
head=p1;
}
p2=p1;
p1=(struct student*)malloc(LEN);
p2->next=p1;
}
p2->next=NULL;
return head;
}
void save(int a,struct student*head)
{
printf("请输入文件名:例[D:\\string.dat]\n");
char m[30];
scanf("%s",m);
struct student*p1,*p2;
intr=1;
p1=p2=(struct student*)malloc(LEN);
FILE*fp;
fp=fopen(m,"w");
fwrite(head,LEN,1,fp); //这里是写入文件。
while(r<a)
{
r=r+1;
p2->next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
fwrite(p1,LEN,1,fp);
}
p2->next=NULL;
}
struct student*input(int a)
{
struct student*head;
struct student*p1,*p2;
head=p1=p2=(struct student*)malloc(LEN);
FILE*f1;
char m[30];
scanf("%s",m);
if((f1=fopen(m,"r"))==NULL)
{
printf("can not be open!\n");
exit(0);
}
intr=0;
while(r<a)
{
r=r+1;
fread(p1,LEN,1,f1); //这里从文件里面读出。
printf("%d\t%s\n\n",p1->NO,p1->name); //将读出的结构体里面的数据输 出到屏幕,可是结果不对,乱码的。
}
return(head);
fclose(f1);
}
void main()
{
struct student*head;
head=NULL;
int a,b;
scanf("%d%d",&a,&b);
head=input(a,b);
save(a,head);
input(a);
}
{
printf("请输入文件名:例[D:\\string.dat]\n");
char m[30];
scanf("%s",m);
struct student*p1,*p2;
int r=1;
p1=p2=(struct student*)malloc(LEN);
FILE*fp;
fp=fopen(m,"w");
//fwrite(head,LEN,1,fp); //这里是写入文件。
fwrite(&head->NO,4,1,fp); //这里是写入文件。
fwrite(head->name,1,5,fp); //这里是写入文件。
while(r<a)
{
r=r+1;
p2->next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
fwrite(p1,LEN,1,fp);
}
close(fp);
}
struct student* output(int a)
{
struct student*head;
struct student*p1,*p2;
head=p1=p2=(struct student*)malloc(LEN);
FILE *fp1;
char m[30];
int NO,n;
char buf[5]={};
printf("输入 文件名 m\n");
scanf("%s",m);
printf("m = %s\n",m);
if((fp1=fopen(m,"r"))==NULL)
{
printf("can not be open!\n");
exit(0);
}
int r=0;
printf("a= %d\n",a);
while(r<a)
{
r=r+1;
n = fread(&NO,4,1,fp1);
printf("n1 = %d\n",n);
printf("%d\n",NO);
n = fread(buf,1,5,fp1);
printf("n2 = %d\n",n);
printf("%s\n",buf);
printf("why ???\n"); //将读出的结构体里面的数据输 出到屏幕,可是结果不对,乱码的。
}
fclose(fp1);
return(head);
}
void main()
{
struct student *head,*p;
head=NULL;
int a,b;
printf("输入 学生数 和 课程数\n");
scanf("%d %d",&a,&b);
head=input(a,b);
save(a,head);
for(p=head;p!=NULL;p=p->next){
printf("%d %s\n",p->NO,p->name);
}
output(a);
}