有个关于fread函数的问题讨教下论坛的高手

C语言 码拜 8年前 (2016-05-06) 740次浏览
刚学C语言不久, 学到文件这里,练习fread函数时遇见一个问题,本来想用fread函数读取文件
内的数据到结构体链表,然后再交给自定义的函数print打印出来。但是对fread函数用了if语句判
断,就会报错,直接用fread却读取正常,本人本人读取了下fread返回的值,发现不加if,返回的值
是正常的,加了if返回的值就不正常,想了半天,没想明白是怎么回事,来向大家求帮助,麻烦大家
帮本人看看是错在哪里了。
代码如下
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define LEN sizeof(struct student)
int n;
struct student
{
long num;
struct student *next;
};
//新建链表
struct student *creat(void)
{
struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student *)malloc(LEN);
printf(“input:”);
scanf(“%ld”,&p1->num);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
p2=p1;
}
p1=(struct student *)malloc(LEN);
printf(“input:”);
scanf(“%ld”,&p1->num);
}
p2->next=NULL;
return(head);
}
//链表输出
void save(struct student *head)
{
FILE *fp;
struct student *p1;
p1=head;
if((fp=fopen(“ceshi.txt”,”wb”))==NULL)
{
printf(“files cannnot be open”);
exit(1);
}
while(p1!=NULL)
{
if(fwrite(p1,sizeof(struct student),1,fp)!=1)
{
printf(“file write error!\n”);
}
p1=p1->next;
}
printf(“record has been wtite down\n”);
fclose(fp);
}
//链表载入
struct student *load()
{
int test;
struct student *head;
struct student *p1,*p2;
head=p2=p1=(struct student *)malloc(LEN);
FILE *fp;
if((fp=fopen(“ceshi.txt”,”rb”))==NULL)
{
printf(“cannot open file”);
getchar();
}
while(1)
{          问题出在这里
//fread(p1,sizeof(struct student),1,fp);     //直接读取没问题
//test=fread(p1,sizeof(struct student),1,fp);  //读取并检查返回的值,也没问题
//if(test==0)
//if((test=fread(p1,sizeof(struct student),1,fp))!=1);  //对fread返回值判断,并检查test,test为1,但是仍触发了if
if(fread(p1,sizeof(struct student),1,fp)!=1); //直接对fread返回值判断, 触发了if
//printf(“fread=%d\n”,test);
{
printf(“file read error!\n”);
getchar();
}
if(feof(fp)) break;
p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
}
p2->next=NULL;
printf(“file load complete\n”);
fclose(fp);
return(head);
}
//链表打印函数
void print(struct student *head)
{
struct student *p;
printf(“the reoced is :\n”);
p=head;
while(p!=NULL)
{
printf(“%ld\n”,p->num);
p=p->next;
}
return;
}
//主函数
main()
{
struct student *p;
//p=creat();
//save(p);
p=load();
print(p);
system(“pause”);
}
解决方案

20

你的if后面貌似多了个分号?

10

链表从文件里读取,很容易啊,读到一个数据,插入链表
很多书中,创建链表就是这么创建的。
链表里面的数据写入数据,也很简单直接写入就是了
唯一比较麻烦的就是链表对数据的管理不方便,需要循环查找
数组就比较方便,可以随机查找
假如真的需要在文件里创建链表,
那就本人做个分配文件位置的函数(包括回收)
可以模拟内存释放和回收
这样就可以内存链表 的数据,写入文件链表了
不过这个要麻烦点

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明有个关于fread函数的问题讨教下论坛的高手
喜欢 (0)
[1034331897@qq.com]
分享 (0)