c - 从文件加载到链表

标签 c data-structures

我正在尝试将未知数量的数据从文件加载到链接列表中

加载函数

void load(FILE *file, Node **head) // while feof somewhere
{
    char tempArtist[30]={'\0'}, tempAlbum[30]={'\0'}, tempTitle[30]={'\0'}, tempGenre[30]={'\0'},tempSpace='\0';
    char tempPlay[100]={'\0'}, tempRating[6]={'\0'}, tempMins[8]={'\0'}, tempSecs[8]={'\0'};

    Data *temp;

    temp=(Data*)malloc(sizeof(Data));

            while(!feof(file))
            {
            fscanf(file,"%s",tempArtist);
            fscanf(file,"%s",tempAlbum);
            fscanf(file,"%s",tempTitle);
            fscanf(file,"%s",tempGenre);
            fscanf(file,"%s",tempMins);
            fscanf(file,"%s",tempSecs);
            fscanf(file,"%s",tempPlay);
            fscanf(file,"%s",tempRating);

            temp->mins=strdup(tempMins);
            temp->secs=strdup(tempSecs);
            temp->album=strdup(tempAlbum);
            temp->artist=strdup(tempArtist);
            temp->genre=strdup(tempGenre);
            temp->song=strdup(tempTitle);
            temp->played=strdup(tempPlay);
            temp->rating=strdup(tempRating);    

            insertFront(head,temp);

            }

}

我遇到的问题是,当我打印列表时,所有条目都与从文件中读取的最后一个条目相同。这与 strdup() 有关,但我无法在不发生访问冲突的情况下将其复制到数据类型。

我可以用来复制从文件中读取的字符串并将其传递给插入的另一种方法(正确的方法)是什么?

插入前面

void insertFront(Node **head, Data *data)
{
    Node *temp=makeNode(data);

    if ((*head) == NULL)
    {
        *head=temp;
    }
    else
    {
        temp->pNext=*head;
        *head=temp;
    }

}

数据结构

typedef struct data
{
    char *artist;
    char *album;
    char *song;
    char *genre;
    char *played;
    char *rating;
    char *mins;
    char *secs;
}Data;

测试文件

snoop
heartbeat
swiggity
rap
03
10
25
4
hoodie
cakeboy
birthday
hiphop
02
53
12
5

最佳答案

您对所有行使用相同的 temp 实例。分配应该在循环内部进行,理想情况下是在您确定整个条目已成功读取之后。

顺便说一下,feofnot a good way to control input loops 。您应该检查 fscanf 的返回值。

while (1) {
    if (fscanf(file,"%s",tempAlbum) < 1 ) break;
    if (fscanf(file,"%s",tempArtist) < 1) break;
    // ...

    temp = (Data *) malloc(sizeof(Data));

    temp->album=strdup(tempAlbum);
    temp->artist=strdup(tempArtist);
    // ...

    insertFront(head, temp);
}

请注意,只有在读取整个记录后,新节点的分配才会发生。

还有其他方法可以改进代码。例如,包含数字数据的字符串的缓冲区非常短。如果出现行错误并且您将较长的行读入如此短的缓冲区怎么办?另外,您的输入似乎是逐行的,因此最好使用 fgets 而不是 fscan(f, "%s"),后者只会读取 "单词”,并且在处理带有空格的行时会出现问题。

关于c - 从文件加载到链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29248867/

相关文章:

c - 添加用户空间头文件以生成文件

c - 矩阵乘法的动态内存分配

c - 在 c 中硬编码大小的最佳方法

c - 如何并行化 Windows 消息循环和 Hook 回调逻辑及其创建的 Ruby 线程?

C 打印二维数组

algorithm - 估计节点在 d-heap 中的插入深度

scala - 如何在保持不变性的同时访问 Scala 中的复杂数据结构?

算法问题: Best angle to view trees from fixed camera

algorithm - 摊销分析和竞赛题,有什么问题吗?

PHP,哎呀;为可变深度的分类项目选择正确的设计模式并显示项目链接