0
struct node 
{
char item[200];
struct node* next;
};

FILE* unionMethod(char f1name[50], char f2name[50])
{
    FILE* f1;
    FILE* f2;

    f1=fopen(f1name,"r");
    f2=fopen(f2name,"r");
    char line[200];
    struct node *head1=NULL;
    struct node *head2=NULL;

    while(!feof(f1))
    {
        fgets(line, 200, f1);
        struct node *cur=head1->next;
        if(head1==NULL)
        {
            head1 = (struct node *) malloc( sizeof(struct node));
            fgets(line,200,f1);
            strcpy(head1->item, line);
            head1->next=NULL;
        }
        else
        {
            cur = (struct node *) malloc( sizeof(struct node));
            fgets(line,200,f1);
            strcpy(cur->item, line);
            cur->next=NULL;
        }
    }

    fclose(f1);
}
int main()
{
    unionMethod("inputfile1.txt","inputfile2.txt");
    return 0;
}

what I am basically trying to do is getting lines from a file and put them into a linked list. However when execution reaches while part program stops, because of "feof" function. I could not understand the problem with this.

Thanks for your help.

ckaan
  • 1
  • 1

1 Answers1

0

This is a very frequent question, just change

while (!feof(f1))

to

while (fgets(line, 200, f1))

the reason is that the EOF marker is set after fgets() attempts to read past the end of the file, so you will need one extra iteration for it to be set.

Community
  • 1
  • 1
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97