C:输出错误链表和写入和读取文件
问题描述:
我试图创建一个包含数字的链表并将这些数字写入一个文件,然后读取相同的文件并读取文件中的数据并打印这些数据数字。C:输出错误链表和写入和读取文件
我该如何认为问题是,读取文件时出现错误。
我已经添加了用于调试的som打印语句,并且在打印正在写入文件的内容时,它看起来没问题。但是当我读取文件并打印时,我得到用户输入的第一个数字打印两次。 例如:
input: 1,2,3
output:3,2,1,1
我真的不知道,如果有一个与我的链表问题,写入文件,或者如果它是阅读。所以,如果能够帮助我更好地理解,我将不胜感激。
由于
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct postTyp
{
int num;
struct postTyp *next;
}postTyp;
FILE *fp;
int main()
{
postTyp *l, *p; //l=list , p=pointer
l = NULL;
p=malloc(sizeof(postTyp));
//Creates linked list until user enters 0
printf("Enter a number, 0 to exit: ");
scanf("%i", &p->num);
while (p->num != 0)
{
p->next=l;
l=p;
p=malloc(sizeof(postTyp));
printf("Enter a number, 0 to exit: ");
scanf("%i", &p->num);
}
free(p);
p=l;
//write the linked list to file
fp = fopen("test.txt", "w");
while(p->next != NULL)
{
printf("%2i", p->num);
fwrite(p, 1, sizeof(postTyp), fp);
p=p->next;
}
printf("%2i", p->num);
fwrite(p, 1, sizeof(postTyp), fp);
fclose(fp);
printf("\n");
//Code below to read the file content and print the numbers
fp = fopen("test.txt", "r");
fread(p,sizeof(postTyp),1,fp);
fseek(fp,0,SEEK_SET);
//The first number entered at the beginning, will be printed twice here.
while(!feof(fp))
{
fread(p,sizeof(postTyp),1,fp);
printf("-----\n");
printf("%i\n", p->num);
}
fclose(fp);
return 0;
}
答
从的fread手册(https://linux.die.net/man/3/fread):
的fread()和错误文件结束之间不区分,并且呼叫者必须使用FEOF(3)和ferror( 3)确定发生了什么。
因此,您必须在打印p-> num之前检查fread返回值。
您对于读取文件时出现错误的想法是正确的:[为什么是“while(!feof(file))”总是出错?](http://stackoverflow.com/questions/5431941/why -is-而-FEOF文件 - 总是错的)。 –
while(p-> tal!= 0)。你在哪里定义了“tal”成员? –
谢谢你们,所有的评论都有助于我们理解!feof的问题 – Taimour