gpt4 book ai didi

c - 在 C 中读取行并将行分隔到链表中

转载 作者:行者123 更新时间:2023-11-30 17:46:03 25 4
gpt4 key购买 nike

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

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

最佳答案

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

  1. 读取足够的数据。
  2. 解析数据。
  3. 从堆中分配内存。
  4. 复制数据。

line变量只是一个临时缓冲区,而char *authorchar *title如果没有分配的内存,变量就无法生存。调用fread()在你的代码中完全是无稽之谈。您已调用fgets() ,这就是您从文件中读取数据的位置。其余的应该只是字符串操作。

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

关于c - 在 C 中读取行并将行分隔到链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19465151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com