在C语言中读取并将行分隔成链表

在C语言中读取并将行分隔成链表,c,text,linked-list,strtok,C,Text,Linked List,Strtok,我有一个如下所示的文本文件: Author; Title Author; Title etc... 我需要打开这个文件,并将其逐行读取到一个链接列表中。到目前为止,我有这个,但我不知道如何使用strtok(),因为它的读取不正确。 有人能帮我吗 #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/st

我有一个如下所示的文本文件:

Author; Title 
Author; Title 
etc...
我需要打开这个文件,并将其逐行读取到一个链接列表中。到目前为止,我有这个,但我不知道如何使用strtok(),因为它的读取不正确。 有人能帮我吗

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

struct node
{
   char* author;
   char* title;
   struct node* next;
};

int main()
{
    struct node *root;   
    struct node *c;     
    root = malloc( sizeof(struct node) );  
    root->next = 0;  
    c = root; 

    FILE *f;
    f = fopen("books.txt", "r");

    char line[255];
    while( fgets( line, sizeof(line),f) != NULL)
    {
        char *token = strtok(line, ";");
        while(token!=NULL)
        {
          fread( &c->author, sizeof( c->author ), 1, f );
          token = strtok(NULL, " ");
        }
        fread( &c->title, sizeof( c->title ), 1, f );
        //printf("%s",&c->author);
    }

    fclose(f);
    return 0;   
}
#包括
#包括
#包括
#包括
#包括
#包括
结构节点
{
char*作者;
字符*标题;
结构节点*下一步;
};
int main()
{
结构节点*根;
结构节点*c;
root=malloc(sizeof(struct node));
根->下一步=0;
c=根;
文件*f;
f=fopen(“books.txt”,“r”);
字符行[255];
while(fgets(line,sizeof(line),f)!=NULL)
{
char*token=strtok(行“;”);
while(令牌!=NULL)
{
fread(&c->author,sizeof(c->author),1,f);
令牌=strtok(空,“”);
}
fread(&c->title,sizeof(c->title),1,f);
//printf(“%s”,&c->author);
}
fclose(f);
返回0;
}

看起来不对。您始终需要:

  • 读取足够的数据
  • 解析数据
  • 从堆中分配内存
  • 复制数据
  • line
    变量只是一个临时缓冲区,而
    char*author
    char*title
    变量如果没有分配的内存就无法生存。调用
    fread()
    在代码中完全是胡说八道。您已经调用了
    fgets()
    ,从该文件中读取数据。其余的应该只是字符串操作

    典型的方法是将
    char*start
    指向您感兴趣的数据的开头,将
    char*end
    指向您感兴趣的数据后面的第一个字符,然后使用
    author=strndup(start,end start)
    请求堆分配的副本,或者使用
    malloc()的组合执行相同的操作
    memcpy()
    strncpy()

    您需要为每个新节点中的作者和标题字段分配内存,然后使用例如
    strcpy
    将字符串复制到这些字段。