简体   繁体   中英

Why is this code not able to read contents from a file into a linked list?

I am unable to understand what the problem is as it isn't giving the correct output

#include <stdio.h>
#include <stdlib.h>
struct node{
    int data;
    struct node*next;
};
void traversal(struct node*ptr){
    while(ptr!=NULL){
        printf("Element is: %d\n",ptr->data);
        ptr=ptr->next;
    }
}
void read(struct node*head){
    FILE*file;
    int val;
    struct node*cur=(struct node*)malloc(sizeof(struct node));
    head=cur=NULL;
    file=fopen("list.txt","r");

    while(fscanf(file,"%d",&val)!=EOF){
        struct node*ptr=(struct node*)malloc(sizeof(struct node));
        ptr->data=val;
        ptr->next=NULL;
        if(head==NULL){
            head=cur=ptr;
        }
        else{
            cur=cur->next=ptr;
        }
    }
    fclose(file);
}
int main(){
    struct node* head;

    //Allocate memory for linked list nodes in heap
    head=(struct node*)malloc(sizeof(struct node));
    read(head);
    traversal(head);
}

The contents of the file is

3
5
6
1
3

The output gives infinite number of lines with not the correct values

Without getting into the implementation of read() , head will remain the same since read() is not modifying it but a copy. You're also nullifying the allocated memory which result in memory leaks.

Since there is no point in allocating head outside read() , I suggest you define it inside to make things more clean, and then return it. Something of this sort:

struct node *read_file() {
        FILE *file;
        int val;
        struct node *prv = NULL;

        struct node *head = (struct node *)calloc(1, sizeof(struct node));;
        if (head == NULL) {
                return NULL;
         }

        file = fopen("list.txt", "r");

        if (fscanf(file, "%d", &val) != EOF) {
                head->data = val;
                prv = head;
        }

        while(fscanf(file, "%d", &val) != EOF){
                struct node *curr = (struct node *)calloc(1, sizeof(struct node));;
                curr->data = val;
                if (prv)
                        prv->next = curr;

                prv = curr;
        }

        fclose(file);
        return head;
}
int main(){
        struct node *head = read_file();
        traversal(head);
}

Don't forget to free the nodes at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM