簡體   English   中英

為什么此代碼無法將文件中的內容讀入鏈表?

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

我無法理解問題所在,因為它沒有提供正確的 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);
}

該文件的內容是

3個
5個
6個
1個
3個

output 給出了無數行,但值不正確

在不進入read()的實現的情況下, head將保持不變,因為read()不是修改它而是一個副本。 您還將使分配的 memory 無效,這會導致 memory 泄漏。

由於在read()之外分配head沒有意義,我建議您在內部定義它以使事情更干凈,然后返回它。 這種東西:

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);
}

不要忘記在最后釋放節點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM