繁体   English   中英

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

[英]Adding data to doubly linked list that is from a file

按照我当前的功能,我只能从文件中读取第一组数据。 我确信这是因为!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数据,否则头部的数据将为任何新记录重写。

因此,为Record内部load功能分配内存,不要使用head->data

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM