【发布时间】: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