【发布时间】:2015-02-09 05:35:01
【问题描述】:
就我目前的功能而言,我只能从文件中读取第一组数据。我确信这是因为 !feof 没有按照我想要的方式运行,但也可能是由于打印列表功能错误造成的,但我不确定。我对使用动态内存非常陌生,所以请耐心等待。
从文件加载
void load(FILE *file, Node *head)
{
char tempArtist[30] = {'\0'}, tempAlbum[30] = {'\0'}, tempTitle[30] = {'\0'}, tempGenre[30] = {'\0'}, tempSpace = '\0';
SongLength *tempLength = NULL;
char tempPlay[100] = {'\0'}, tempRating[6] = {'\0'}, tempMins[3] = {'\0'}, tempSecs[3] = {'\0'};
tempLength = (SongLength *)malloc(sizeof(SongLength));
while (!feof(file))
{
while (head->pNext == NULL) // Here is where I need to shift to the next node
{
fscanf(file, "%s", &tempArtist);
fscanf(file, "%c", &tempSpace);
strcpy(tempLength->mins, tempMins);
strcpy(tempLength->secs, tempSecs);
strcpy(head->data->artist, tempArtist);
strcpy(head->data->length->mins, tempLength->mins);
strcpy(head->data->length->secs, tempLength->secs);
insertNode(head, head->data);
}
}
free(tempLength);
}
插入链表
void insertNode(Node *head, Record *data)
{
while(head->pNext == NULL)
{
head=head->pNext;
}
head->pNext=(Node*)malloc(sizeof(Node));
head->pNext->data = (Record*)malloc(sizeof(Record));
head->pNext->data->length=(SongLength*)malloc(sizeof(SongLength));
(head->pNext)->pPrev=head;
head=head->pNext;
head->data=data;
head->pNext=NULL;
}
打印列表中的所有数据(希望如此)
void display (Node *head)
{
while (head->pNext != NULL)
{
printf ("Artist: %s\n", head->data->artist);
printf ("Length(mm:ss) %s:%s\n", head->data->length->mins,head->data->length->secs);
head=head->pNext;
}
putchar ('\n');
}
我已经删除了 fscanf() 和 printf() 中的一个,以减少代码。
结构
typedef struct songlength
{
char mins[3];
char secs[3];
}SongLength;
typedef struct record
{
char artist[30];
struct songlength *length;
}Record;
typedef struct node
{
struct node *pPrev;
struct record *data;
struct node *pNext;
}Node;
【问题讨论】:
-
@Gopi 如果我不使用 feof,那么我可以用什么来判断我是否在文件末尾?
-
关于在 C 中调用 malloc() 1),不要从 malloc(和家族)转换返回值 2) 始终检查返回值以确保操作成功 (!= NULL)
-
在 insertNode 函数中,始终检查 '*head' 是否为 NULL,并在它为 NULL 时处理特殊情况,并且参数 'node *head' 应该可能是 'node **head' 所以插入第一个节点时可以更改头指针
-
@user3482104 这个问题必须精心设计,以便任何阅读它的人都知道问题出在哪里..如果您粘贴一些 API 并询问有什么问题,可能很难回答它.. 使用
while(fscanf("%s %c",&tempArtist,&tempSpace) == 2)读取到文件末尾
标签: c linked-list