簡體   English   中英

c中的鏈接列表(從文件中讀取)

[英]Linked list in c (read from file)

我對C編程很新,我遇到了一些困難。 我正在嘗試從行讀取行到文本文件,然后將每行添加到一個簡單的鏈接列表。 我已經嘗試了很多,但我還沒有找到解決方案。 到目前為止,在我的代碼中,我能夠從文件中讀取,但我無法理解如何為行保存文本行並將其添加到鏈接列表中。

這是我到目前為止:

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

如果有人能給我一些關於我接下來要做什么的指示,我會非常感激。 我已經習慣了Java,不知怎的,我的大腦無法理解如何在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;
}

暫無
暫無

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

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