I wrote a C code to implement a dictionary using linked-list(nodes are in sorted order) I want to save the data to a file and be able to reload the data when I run the program next time. I'm having trouble loading the data from file. Here is my code for reading and writing data:
struct node{
char word[20];
char meaning[5][100]; //2D array for saving multiple meanings of a word
struct node *next;
};
void ReadData(struct node *head)
{
struct node *tail;
FILE *fp = fopen("dictionary.data", "rb");
if(fp == NULL)
{
printf("Error opening file..\n");
return;
}
while(!feof(fp))
{
tail = (struct node*)calloc(1, sizeof(struct node));
fread(tail->word, sizeof(head->word), 1, fp);
fread(tail->meaning, sizeof(head->meaning), 1, fp);
if(head == NULL) //for fresh run head is initialized with NULL
{
tail->next = head;
head = tail;
}
else
{
head->next = tail;
head = head->next;
}
}
fclose(fp);
}
I can't load data from the file to the linked list. Code is not working. I can't figure out where the problem is..
Here's how I'm writing the data to the file :
/*I think this code is working because size of the file increases after running the code*/
void WriteData(struct node *head)
{
FILE *fp = fopen("dictionary.data", "wb");
if(fp == NULL)
{
printf("Error opening file..\n");
return;
}
while(head != NULL)
{
fwrite(head->word, sizeof(head->word), 1, fp);
fwrite(head->meaning, sizeof(head->meaning), 1, fp);
head = head->next;
}
fclose(fp);
}
I've used sizeof, instead of strlen, it's a string. It'll have null character at the end - no problem with string. It'll consume more memory though.
freadReadDatareading is done byfreadif-elsepart is for fixing the links between the nodeselseparthead->next = tailassigns the address of new node to thenextfile of the node pointed byhead. Now we have to point the head to the new node(tail), address of the new node is assigned to thenextfiled of the previous node(head->next = tail). So in order to point theheadto the new node I usedhead = head->nextashead->next=address oftailhead->nextholds the address oftailheadin the function. InReadData, no argument is necessary.headshould be returned.