【问题标题】:Linked list in c (read from file)c中的链表(从文件中读取)
【发布时间】:2014-11-02 23:18:28
【问题描述】:

我对 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 来做这些事情。

【问题讨论】:

  • char string; 是一个单字节变量。它只能存储 8 位数据,不能存储任何类型的文本字符串。你可能想要char *string;。也许您可以尝试使用strdup() 在读取每个字符串时创建一个副本,并将返回值分配给每个链接的string 元素。 Reading this might help.

标签: c file-io linked-list


【解决方案1】:
#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;
}

【讨论】:

  • 不释放每个节点会发生什么?
  • 现代操作系统释放在程序结束时分配的内存。所以,它不会发生,尤其是任何事情。也许:-)
  • 为了避免segmentation fault错误,需要指定字符串的大小:struct list { char string[128];结构列表*下一个; };
  • 这是错误的建议。它应该检查返回值而不是这样做。
猜你喜欢
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 2017-05-03
相关资源
最近更新 更多