C语言这段用fwrite写入和用fread读出函数的程序哪里错了?

#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
struct student
{
int num;
char name[10];
char password[15];
char sub[10][15];
float score[10][2];
struct student * next;}; /定义一个结构体/

struct student stu1,stu2,*p,*head;
FILE *fp;
int i,n=2;
memset(&stu1,0,sizeof(struct student));
memset(&stu2,0,sizeof(struct student));

stu1.num=1;
strcpy(stu1.name,"mary");
strcpy(stu1.password,"abc");
strcpy(stu1.sub[0],"math");
stu1.score[0][0]=99;
stu1.next=&stu2;
stu2.num=2;
strcpy(stu2.name,"bob");
strcpy(stu2.password,"abc");
strcpy(stu2.sub[0],"math");
stu2.score[0][0]=98;
stu2.next=NULL; /构件一个链表/

if((fp=fopen("student1.dat","wb"))==NULL)printf("111111111");
if((fwrite(&stu1,sizeof(struct student),1,fp))!=1)printf("33");
if((fwrite(&stu2,sizeof(struct student),1,fp))!=1)printf("44"); /写入/
fclose(fp);
if((fp=fopen("student1.dat","wb+"))==NULL)printf("aaaaaaaaaa");
fseek(fp,0,SEEK_SET); /文件指针归零/
for(i=0;i<n;i++)
{
if((p=(struct student *)malloc(sizeof(struct student)))==NULL)printf("gggg");
memset(p,0,sizeof(struct student));

if((fread(p,sizeof(struct student),1,fp))!=1)printf("bbbb"); /读出/
printf("%d",p->num); /输出/

p=p->next; /构件链表关系/ }

fclose(fp);

return 0;
}

但是输出的结果是“bbbb0”也就貌似是读出出错了。。。

谢谢了!我一共只有这么点分。。。。

第1个回答  2014-12-08
w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。

fp=fopen("student1.dat","wb+")),你的第二次打开文件用的是w+,那岂不是文件又被清零了?

应该改成
(fp=fopen("student1.dat","rb+"))

对fopen参数的解释:
r 以只读方式打开文件,该文件必须存在。
r+ 以可读写方式打开文件,该文件必须存在。
w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。本回答被提问者采纳
第2个回答  2014-12-08
注释方法是错误的,要用/* */ 或 //
修改以上之后,代码可以编译通过,但,真心看不懂
一、结构体,不明白它的定义意图
二、代码内容,看不懂目的所在
相似回答