C语言 文件读取问题
#include"stdio.h"#include"conio.h"
typedef struct node
{
char name[50];
long num;
int math,eng,phy,sum;
float average;
struct node *next;
}linklist,*list;
void insert(list L)
{
long x; FILE *out;
list p,r; r=L;
out=fopen("stu.dat","ab");
printf("please input the Number(press 0 to quit):");
scanf("%ld",&x);
while(x){r=L; p=(list)malloc(sizeof(linklist));
if(L->next!=NULL)
{ while(r->next!=NULL&&x>r->next->num)
{r=r->next;}
if(r->next!=NULL&&r->next->num==x)
{printf("this num is exist\n"); free(p);p=NULL; }
}
if(p!=NULL){
printf("please input the name:");
getchar(); gets(p->name);
printf("please input the math:");
scanf("%d",&p->math);
printf("please input the eng:");
scanf("%d",&p->eng);
printf("please input the phy:");
scanf("%d",&p->phy);
p->num=x;
p->sum=p->math+p->eng+p->phy; p->average=(float)p->sum/3;
p->next=r->next;
r->next=p;
fseek(out,sizeof(linklist),1);
fwrite(p,sizeof(linklist),1,out); }
printf("please input the Number(press 0 to quit):");
scanf("%ld",&x);
}
fclose(out);
}
void output(list L)
{
list r; r=L->next;
if(r==NULL) {printf("this list is empty\n");return;}
while(r!=NULL)
{ printf("----------------------");
printf("the num is:%ld",r->num);
printf("-------------------------------\n");
printf("name:%s",r->name);
printf(" math:%d",r->math);
printf(" eng:%d",r->eng);
printf(" phy:%d",r->phy);
printf(" sum:%d",r->sum);
printf(" ave:%.3f\n\n",r->average);
r=r->next; }
}
void file(list L) /*文件读取函数*/
{FILE *in;
list p,r;
r=L;
if((in=fopen("stu.dat","rb"))==NULL)
printf("file is't exist please insert the information first\n");
else{while(!feof(in))
{ p=(list)malloc(sizeof(linklist));
fread(p,sizeof(linklist),1,in);
p->next=NULL;
r->next=p;
r=r->next;
}
printf("the file has been load\n");
fclose(in);
}
}
void main()
{ list L; int t=-1;
L=(list)malloc(sizeof(linklist));
L->num=L->math=L->eng=L->phy=L->average=L->sum=-1;
L->next=NULL;
file(L);
if(L->next==NULL) insert(L);
output(L);
insert(L);
output(L);
getch();
}
问题1.写入函数,插入什么都没问题,就是每次读取文件时会多读一条,在有的电脑上多读一条的学生信息全是 0 ,有的电脑上就全是不规则的。
问题2.还有一个问题:读取函数的 fread(p,sizeof(linklist),1,in); 在循环时并没有用文件移位函数啊,in不是始终指向文件头么,那应该只读最开头的信息啊,但运行时为什么会自动移位呢,会把存入的信息全读出来,是为什么呢?
文件的那些不是很懂,谢谢了,都是二进制的读取,我用文本存取的话就读出更多0了。
[ 本帖最后由 goto09 于 2011-4-17 18:07 编辑 ]