C语言从文件读取问题

下面是我写的一段从读取文件内容再打印到屏幕的一段代码,但是打印的每行最后2个数总是不正确。用txt文件也是这样。
希望有高手来解释下。。。。。。。。。
void print_list()
{
student *head=read_list();
if(head==NULL) printf("文件无记录!");
while(head!=NULL){
printf("%d %s %.1f %.1f %.1f %.1f\n",head->num,head->name,head->math,head->eng,head->c_l,head->score);
head=head->next;
}
}

student *read_list()
{
student *head,*link,*p;
FILE *f;

if((f=fopen("student.xls","r"))==NULL){
printf("文件打开错误!\n");
exit(0);
}

head=link=NULL;
while(!feof(f)){
p=(student *)malloc(sizeof(student));
fscanf(f,"%d%s%f%f%f%f\n",&p->num,p->name,&p->math,&p->eng,&p->eng,&p->c_l,&p->score);
if(head==NULL){
head=p;
}
else link->next=p;
link=p;
p->next=NULL;
}

fclose(f);

return head;
}

有一个问题是"fscanf(f,"%d%s%f%f%f%f\n",&p->num,p->name,&p->math,&p->eng,&p->eng,&p->c_l,&p->score);" 这一行对p->eng读了两次,导致后面数据错了。
改为“fscanf(f,"%d%s%f%f%f%f\n",&p->num,p->name,&p->math,&p->eng,&p->c_l,&p->score);"试试看。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-12-05
如果你程序没问题的话,输入到屏幕是不会错的,那就是你那个文件读的时候的问题。
1.可能是你那个文件,那个文件是你手写进去的还是用fprintf写进去的?如果是手写的可能就出现上述问题
2.对于读写文件用fscanf和fprintf不是很好,尤其是这种读成块的数据的时候,我推荐使用fread和fwrite成块的读取和写入。用法为fread(存放地址,读的字节数,读多少个数据块,文件指针),fwrite相似。
由于你程序没给全我也只能这样了,如果你把程序都说出来就哦了
相似回答