帮忙看看这个程序 C语言

2025-02-26 18:13:12
推荐回答(1个)
回答1:

date时日期啊,通常数据会取名叫data才对吧。麻烦下次改过来。居然叫这个名字唬了半天……a和e实在太难区分了……

1 链表构建的逻辑有问题,q根本没移动到下一个节点上,所以链表里面最多只有两个节点存在。实际上q没必要存在,我把它干掉了。
2 fp怎么会变成EOF?EOF是fscanf返回的,换掉了。
3 既然都判断文件读取失败的情况了,那就做的漂亮一点,不要进行无谓的内存分配,也不要让处理部分在打不开文件的时候操作了,现实世界的系统如果这样写会死的很惨。我重新整理了一下,打开文件的代码放到一起,处理的代码放到一起,以后改起来也方便。
4 实际上这段程序多分配了一次内存,那里面只保存了next=NULL,其实可以优化掉,这个我没改,你自己优化看看吧。

#include
#include

typedef struct employee
{
int age;
char name[10];
float salary;
struct employee *next;
} Men;
FILE *fp;
int main()
{
Men *head,*w;

if(!(fp=fopen("date.txt","r")))
{
printf("can not open the file\n");
return;
}
else
printf("OK\n");

head=(Men *)malloc(sizeof(Men));
w=head;

while(fscanf(fp,"%d%s%f",&w->age,w->name,&w->salary)!=EOF)
{
w->next=(Men *)malloc(sizeof(Men));
w=w->next;
};
w->next=NULL;
fclose(fp);
w=head;
while(w->next!=NULL)
{
printf("age:%d\n",w->age);
printf("name:%s\n",w->name);
printf("salary:%f\n",w->salary);
w=w->next;
}

}