-
read/write linked list
I want to write the data that the linked list holds to disk. I believe the function that writes the data is code correctly. Its reading that I have problems with. I take my problem is that headRef is local. How would I get around this?
Code:
struct node {
int data;
struct node* next;
};
int saveList(struct node** headRef, char* filename)
{
struct node* current = *headRef;
FILE *fp;
if(current == NULL)
return 1;
fp = fopen(filename,"wb");
if(fp == NULL)
return 2;
while(current != NULL)
{
fwrite(¤t->data, sizeof(struct node), 1 , fp);
current = current->next;
}
fclose(fp);
return 0;
}
/**********************************************************/
int loadList(struct node** headRef, char* filename)
{
struct node* current = *headRef;
int data;
FILE *fp = fopen(filename,"rb");
if(fp == NULL)
return 1;
while(fread(&data, sizeof(struct node), 1, fp) != 0)
{
addToList(¤t,data);
}
fclose(fp);
return 0;
}
-
You are writting too much data: "fwrite(current->data,sizeof(struct node),1,fp)" - the size of the structure is not the size of data.
gg
-
so what you are saying to use sizeof(int) instead of sizeof(struct node)?
[edit]
Ok, so I did that. After deleting the list and then loading it back from disk it says the data isn't being added to the list.
[/edit]
-
If data is an int, then yes.
gg
-
>>Ok, so I did that.
Did you do it on both the fread and fwrite?
Post your revised code if you still have problems.