gpt4 book ai didi

c - 将数据添加到来自文件的双向链表

转载 作者:行者123 更新时间:2023-11-30 15:24:26 24 4
gpt4 key购买 nike

就我当前的功能而言,我只能从文件中读取第一组数据。我确信这是因为 !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;

最佳答案

函数调用 insertNode(head,head->data); 看起来很奇怪。第二个参数必须是不是来自 head 的数据,否则 head 中的数据将被重写以用于任何新记录。

因此,请在 load 函数内为 Record 分配内存,并且不要使用 head->data

关于c - 将数据添加到来自文件的双向链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28403409/

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