Reputation: 25
Im trying to create a linked list containing numbers and write those numbers to a file, and then read the same file and read the data within the file and print those numbers.
What I think the problem is, is that there's something wrong when reading the file.
I've added som print statements for debugging, and when printing what I'm writing to the file, it looks ok. But when I'm reading the file and printing I get the first number the user entered printed twice. ex:
input: 1,2,3
output:3,2,1,1
I don't really know if there's a problem with my linked list, writing to file or if it's the reading. So I would appreciate any kind of input that would help me to better understand.
Thanks
#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;
}
Upvotes: 0
Views: 47
Reputation: 257
From the fread manual (https://linux.die.net/man/3/fread):
fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.
So, you have to check the fread return value before printing p->num.
Upvotes: 2