Hi everyone. I am having a trouble with linked list program. This program will read a file with names and store them in a two lists. Then I need to make a linked list and then write them back to the file, seems that the problem is inside of a while loop, I don't understand why it's not working
Here is the code, thank you.
Code:
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#define CHARS 30
#define NAMES 20
int main(void)
{
int count=-1;
int index1=0,index2=0, i=0;
char list1[NAMES][CHARS],list2[NAMES][CHARS];
//char *l1, *l2;
struct NODE {
char name[CHARS];
struct NODE *next;
};
typedef struct NODE Node;
FILE *fp, *out;
Node* head;
Node *curr, *n;
head=(Node*)malloc(sizeof(Node));
curr=head;
//l1=list1;
//l2=list2;
/* open the file and load the strings into 2 arrays */
if((fp=fopen("merge.dat","r"))==NULL)
printf("Cannot open file fot reading");
//exit(1);
while (!feof(fp))
{
count++;
fscanf(fp,"%s %s ",list1[count],list2[count]);
}
fclose(fp);
/*copys names from both lists until one of the lists is finished*/
while(index1<=count||index2<=count)
{
curr->next=(Node*)malloc(sizeof(Node)); /*allocate space for next node*/
curr=curr->next; /* point curr to new allocated space*/
if(strcmp(list1[index1], list2[index2])>0) /*compare list1 and list2*/
{
strcpy(curr->name, list1[index1]);
++index1;
//++l1;
}
if(strcmp(list1[index1], list2[index2])<0)
{
strcpy(curr->name, list2[index2]);
++index2;
//++l2;
}
}
/*finish off the list that isn't finished*/
for(i=index1; i<=count; ++i)
{
curr->next=(Node*)malloc(sizeof(Node));
curr=curr->next;
strcpy(curr->name, list1[index1]);
}
for(i=index2; i<=count; ++i)
{
curr->next=(Node*)malloc(sizeof(Node));
curr=curr->next;
strcpy(curr->name, list2[index2]);
}
curr->next=NULL;
curr=head;
while(curr!=NULL)
{
printf( "%s\n", curr->name);
curr=curr->next;
}
/*writing list back to the file*/
if((out=fopen("merge.dat","w"))==NULL)
printf("Cannot open file for writing\n");
while(curr!=NULL)
{
fprintf(out, "%s\n", curr->name);
curr=curr->next;
}
fclose(out);
for (curr = head; curr != NULL; curr=n)
{
n = curr->next;
free(curr);
}
return 0;
}