0

我正在尝试解析 CSV 文件并将值放入结构中,但是当我退出循环时,我只返回文件的值。我不能使用 strtok,因为 csv 文件中的某些值是空的,它们会被跳过。我的解决方案是 strsep,当我在第一个 while 循环中时,我可以打印所有歌曲,但是当我离开它时,它只会返回文件的最后一个值。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apue.h"

#define BUFFSIZE 512

typedef struct song{
    char *artist;
    char *title;
    char *albumName;
    float duration;
    int yearRealeased;
    double hotttness;
} song;

typedef song *songPtr;

 int main(){
     FILE *songStream;
     int count = 0;
     int size = 100;
     char *Token;

     char *buffer;
     song newSong;
     songPtr currentSong;
     songPtr *allSongsArray = malloc(size * sizeof(songPtr));
     buffer = malloc(BUFFSIZE+1);

     songStream = fopen("SongCSV.csv", "r");

     if(songStream == NULL){
         err_sys("Unable to open file");
     }else{
         printf("Opened File");
             while(fgets(buffer, BUFFSIZE, songStream) != NULL){
                 char *line = buffer;
                 int index = 0;

                 while ((Token = strsep(&line,","))) {
                     if(index == 17){
                         newSong.title = malloc(sizeof(Token));
                         newSong.title = Token;
                     }
                     index++;
                 }
                 currentSong = malloc(1*sizeof(song));
                 *currentSong = newSong;
                 allSongsArray[count] = malloc(sizeof(currentSong) + 1);
                 allSongsArray[count] = &newSong;
                 free(currentSong);
                 printf("\n%s\n", allSongsArray[count]->title);
                 count++;

                 if(count == size){
                     size = size + 100;
                     allSongsArray = realloc(allSongsArray ,size * sizeof(songPtr));
                 }
             }
             fclose(songStream);
     }

     fprintf(stdout,"Name in struct pointer array:  %s\n",allSongsArray[2]->title);


     return 0;
 }

有人可以告诉我为什么会发生这种情况以及如何解决吗?

4

1 回答 1

1

您应该更改newSong.title = Token;为 指向缓冲区strcpy(newSong.title,Token);Token的一个地址,该地址将在读取下一行时保存新数据

它也将避免内存泄漏

newSong.title = malloc(sizeof(Token));

只会分配 sizeof(char *) 字节,因此您分配的字节数少于您需要的字节数,如果令牌超过 4 或 8 个字节,这可能会导致分段,具体取决于系统上的 sizeof(char *)

             *currentSong = newSong; 
             allSongsArray[count] = malloc(sizeof(currentSong) + 1); 
             allSongsArray[count] = &newSong;
             free(currentSong);

将其更改为

memcpy(currentSong,&newSong,sizeof(newSong));
allSongsArray[count] = currentSong;
于 2017-09-14T04:47:27.877 回答