Linked list in c (read from file)

后端 未结 1 551
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 17:28

I\'m very new to C-programming, and I\'m having some difficulties. I\'m trying to read line from line to a text file, and then add each line to a simple linked list. I have

1条回答
  •  时光说笑
    2020-12-30 17:55

    #include 
    #include 
    #include 
    
    struct list {
        char *string;
        struct list *next;
    };
    
    typedef struct list LIST;
    
    int main(void) {
        FILE *fp;
        char line[128];
        LIST *current, *head;
    
        head = current = NULL;
        fp = fopen("test.txt", "r");
    
        while(fgets(line, sizeof(line), fp)){
            LIST *node = malloc(sizeof(LIST));
            node->string = strdup(line);//note : strdup is not standard function
            node->next =NULL;
    
            if(head == NULL){
                current = head = node;
            } else {
                current = current->next = node;
            }
        }
        fclose(fp);
        //test print
        for(current = head; current ; current=current->next){
            printf("%s", current->string);
        }
        //need free for each node
        return 0;
    }
    

    0 讨论(0)
提交回复
热议问题