[英]Parsing CSV file into Structs using C
我正在嘗試解析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;
}
有人可以告訴我為什么會這樣以及如何解決嗎?
您應該更改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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.