【问题标题】:reading and separating lines into linked list in C在C中将行读取并分隔到链表中
【发布时间】:2013-10-19 10:43:46
【问题描述】:

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

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

【问题讨论】:

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

标签: c text linked-list strtok


【解决方案1】:

看起来不对。你总是需要:

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

line 变量只是一个临时缓冲区,而char *author 和char *title 变量在没有分配内存的情况下无法生存。在您的代码中调用 fread() 完全是一派胡言。你已经调用了fgets(),这是你从文件中读取数据的地方。其余的应该只是字符串操作。

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

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多