【发布时间】:2017-01-03 12:52:16
【问题描述】:
我试图创建一个包含数字的链表并将这些数字写入文件,然后读取同一个文件并读取文件中的数据并打印这些数字。
我认为的问题是,读取文件时出现问题。
我为调试添加了一些打印语句,当打印我正在写入文件的内容时,它看起来没问题。但是当我阅读文件并打印时,我得到用户输入的第一个数字打印了两次。 例如:
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;
}
【问题讨论】:
-
您认为阅读文件时出错的想法是正确的:Why is “while ( !feof (file) )” always wrong? 可能重复。
-
while (p->tal != 0)。你在哪里定义了“tal”成员?
-
谢谢大家,所有 cmets 在理解 !feof 的问题时都提供了帮助
标签: c struct linked-list fwrite fread