由于我当前的功能,我只能从文件中读取第一组数据。我确信这是因为!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()之外,我删除了所有内容以减少代码。
的Structs
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;
答案 0 :(得分:1)
函数调用insertNode(head,head->data);
看起来很奇怪。第二个参数必须是来自head
的数据,否则将为任何新记录重写head中的数据。
因此,在Record
函数内为load
分配内存,不要使用head->data
。