求指点:C语言链表读文件有关的问题!! 着急坐等!!!!!!

maspacious 2012-11-25 02:54:52
我用fwrite写到文件,但是用fread读取的时候第一行总是有一段乱码
对链表的读写不是很懂 也是照着网上自己改的 怎样避免出现乱码?求指点

#include <stdio.h>
#include <stdlib.h>
typedef struct StuNode
{
int num;
char name[20];
char sex[4];
int english_score;
int c_score;
struct StuNode *next;
}StuList;

void main()
{
StuList *input();
void read_file();
void write_file(StuList *head);

StuList *head;
head=input();
write_file(head);
read_file();

system("pause");
}

StuList *input()
{
int x;
bool z=true;
StuList *head,*stu;
head = NULL;
while(z)
{
stu = (StuList*)malloc(sizeof(StuList));
scanf("%d%s%s%d%d",&stu->num,&stu->name,&stu->sex,&stu->english_score,&stu->c_score);
stu->next = head;
head=stu;
printf("是否继续输入下一项记录(1、继续 2、退出):");
scanf("%d",&x);
if(x == 1)
{
z=true;
}
else if( x == 2)
{
z=false;
}
}
return head;
}
void write_file(StuList *head)
{
FILE *fp;
if((fp=fopen("student.txt","a")) == NULL)
{
printf("加载失败!");
return;
}
for (head ; head != NULL ; head = head->next)
{
fwrite(head,sizeof(StuList),1,fp);
}
fclose(fp);
}
void read_file()
{
StuList *head,*stu,*r,*t; //改动:添加*t,作为标记
FILE *fp;
if((fp=fopen("student.txt","r"))==NULL)
{
printf("加载失败!");
}
head=r=(StuList*)malloc(sizeof(StuList));
while(!feof(fp))
{
stu=(StuList*)malloc(sizeof(StuList));;
fread(stu,sizeof(StuList),1,fp);
r->next=stu;
t=r;
r=stu;
}
t->next=NULL;//改动,添加*t
fclose(fp);
if(head == NULL)
{
printf("没有数据!");
}
else
{
for( head ;head != NULL;head = head -> next )
printf("学号:%5d 姓名:%5s 性别:%5s 英语成绩:%5d C语言成绩:%d\n",
head->num,head->name,head->sex,head->english_score,head->c_score);
}
}
...全文
130 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
转角天边 2012-11-25
  • 打赏
  • 举报
回复
建议 scanf("%d%s%s%d%d",&stu->num,&stu->name,&stu->sex,&stu->english_score,&stu->c_score); 这个中间加点空格 scanf("%d %s %s % d %d",&stu->num,&stu->name,&stu->sex,&stu->english_score,&stu->c_score); 以区分输入的是哪个
转角天边 2012-11-25
  • 打赏
  • 举报
回复
for( head ;head != NULL;head = head -> next ) 改成 for( head=head->next ;head != NULL;head = head -> next )

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧