-
Filling a linked list
Code:
datafile=fopen("data.abd","r");
if(datafile!=NULL){
firstp=malloc(sizeof(struct person));
currentp=firstp;
while(1){
newp=malloc(sizeof(struct person));
fread(currentp,sizeof(currentp),1,datafile);
if(currentp->next==NULL){
break;
}
currentp->next=newp;
currentp=newp;
}
fclose(datafile);
}
This should fill the linked list from a file called "data.txt". For some reason it only fills in the first one. Why?
~Sven
-
malloc does not null its values when called. All it does is give you a pointer to some place in memory. Just like local non-static variables, they're unintialized upon creation, and contain some random data. That said, you're doing this pretty much ass backwards.
You should be looping based on the return value of fread, not on if what you've happened to read has somehow magically set the 'next' pointer to NULL or not.
Quzah.
-
This is from a file that was already printed from a linked list. I make the linked list in my program and then fwrite it into "data.txt" and read it back next time the program is run. So if currentp->next was NULL when it was printed into the file shouldn't it be NULL when it comes back out?
~Sven
-
[edit]
Change your if() to test the return value of fread(), as suggested by Quzah.
[/edit]
-
But I read the structure from the file into currentp. So doesn't it have that stuff in it?
~Sven
-
Code:
fread(currentp,sizeof(currentp),1,datafile);
You might want sizeof(*currentp).
-
Oh, I had that in my program I must have mistyped it into here. How do I make this work though?
~Sven
-
OK I got it. I read through my program a few times and realized that I was writing the entries to the file as soon as they were made. So they were the last entries causing their pointer to be NULL when in the file so it stopped at the first one everytime. Stupid mistake.
~Sven
-
> Oh, I had that in my program I must have mistyped it into here. How do I make this work though?
Here's a tip - use copy/paste of your actual code.
Simply typing here what you think you have isn't good enough. You only need to be off by a very small number of characters before the advice goes off in a completely different direction to your actual problem.