由于总代码长度过长,显示部分代码块。
/*将文件内的内容读入到链表中*/
struct worker_link *pNew;
struct worker_link *pTail = NULL;
char eat = ' ';
while (!feof(fp1))
{
pNew = (struct worker_link *)malloc(sizeof(struct worker_link));
if(pNew == NULL)
{
printf("Error!");
exit(-1);
}
fscanf(fp1, "%s%c%s%c%c%c%d%c%s%c%s%c", pNew->work_num, &eat, pNew->name, &eat, &pNew->sex, &eat, &pNew->position_num, &eat, pNew->birthday, &eat, pNew->add, &eat);
if(pHead == NULL)
pHead = pNew;
else
pTail->pNext = pNew;
pTail = pNew;
}
pTail->pNext = NULL; //链表结尾要把尾指针的pNext指针置空
p = pHead;
fclose(fp1);
C语言在读取文件的时候多读取了最后一行。导致数据总是多了一个0,求助解决方案
问题出在这里:while (!feof(fp1))前没有读取文件的语句,feof(fp1)要在逻辑上跟在读语句之后才能正确判断,你还没有读文件,判断什么结束没有不就多出一行了?改法很多,最简单的是把while (!feof(fp1))改成while (1),在fscanf语句后面加一句加一句if(feof(fp1)) break;。
温馨提示:答案为网友推荐,仅供参考