我正在尝试解析 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;
}
有人可以告诉我为什么会发生这种情况以及如何解决吗?