简体   繁体   中英

Linked list in c (read from file)

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 tried a lot, but I haven't found a solution. So far in my code I'm able to read from the file, but I can't understand how to save the text line for line and add it to the linked list.

This is what I have so far:

struct list {
char string;
struct list *next;
};

typedef struct list LIST;

int main(void) {

    FILE *fp;
    char tmp[100];
    LIST *current, *head;
    char c;
    int i = 0;
    current = NULL;
    head = NULL;
    fp = fopen("test.txt", "r");

    if (fp == NULL) {
        printf("Error while opening file.\n");
        exit(EXIT_FAILURE);
    }

    printf("File opened.\n");

    while(EOF != (c = fgetc(fp))) {
       printf("%c", c);
    }

    if(fclose(fp) == EOF) {
        printf("\nError while closing file!");
        exit(EXIT_FAILURE);
    }
    printf("\nFile closed.");
}

If anyone could give me some pointers on what I need to do next to make it work, I would highly appreciate it. I'm used to Java, and somehow my brain can't understand how to do these things in C.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

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