c - 从文件中获取数据并将其添加到 C 中的链接列表中

标签 c list file linked-list fopen

#include<string.h>
#include<stdio.h>
    
struct Friend{
    char name[50];
    char surname[50];
    char gender;
    char date[50];
    struct Friend * next;
};

struct Friend* initialize(char *);

int main(){
    char name[100];
    printf("ENter the name of the file\n")
        gets(name);
    struct Friend * head;
    head=initialze(name);
    
}

struct Friend * initialize(char *name){
    FILE * ffile;
    ffile=fopen(name,"r");
    if(ffile==NULL)
        exit(1);
}    
   

这是我在 C 中的函数初始化。我需要获取并打开一个文件(该文件的外观示例如下),并创建一个链接列表,其中包含每个人的姓名、性别和出生日期,并返回链表的(HEAD指针)起始地址。我通过一次获取一个字符并使用 3 个嵌套的 while 循环完成了任务。但正如您可能已经猜到的,这是一个非常低效的解决方案。

文件的名称并不重要,因为我提示用户写入它。但这是文件的样子

John;Lenny;M;13/01/1978;

Josh;Bush;M;15/05/1989;

Anjelica;Victoria;F;20/10/1990;

如您所见,每个元素后面都有一个分号(;)

最佳答案

我的处理方式有点不同。 您可以将整个文件读取到缓冲区,也可以在每次遇到“\n”时读取并存储 然后,您必须有一个方法来创建所需结构的节点并填充您刚刚读取的当前行的数据。

例如:

void create(Friend* Head)
{
  struct Friend *new_node = malloc(sizeof(Friend));

  new_node->whatever = whatever;

  Head->Next = new_node;

}

关于c - 从文件中获取数据并将其添加到 C 中的链接列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47251802/

相关文章:

java - 从 Uri 获取路径

html - 在 ion-list 中滚动换行文本

c - 对c中的指针进行两次逻辑否定有什么意义?

c - 微 Controller 在 malloc 失败

c - C中两个字符串的字母顺序比较

Python:可以解包元组并在一行中附加到多个列表吗?

r - 如何通过R中的字典映射列

java - 读取和写入文件时,输出会发生变化

python - 如何在Python中复制文件?

c++ - 退出控制台 "FreeConsole (void)"、 "return 0"或 "exit (EXIT_SUCCESS)"哪个更好?