Parsing CSV file into Structs using C -


i trying parse csv file , put values struct, when exit loops returned value of file. can't use strtok because of values in csv file empty , skipped over. solution strsep, , can print songs while i'm inside first while loop when leave returns me last value of file.

#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 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;  } 

can please tell me why happening , how fix it?

you should change newsong.title = token; strcpy(newsong.title,token); token pointing 1 of addresses buffer going hold new data when next line read

also avoid memory leak

newsong.title = malloc(sizeof(token)); 

will allocate sizeof(char *) bytes have allocated less bytes need, lead segmentation if token more 4 or 8 bytes depending on sizeof(char *) on system

             *currentsong = newsong;               allsongsarray[count] = malloc(sizeof(currentsong) + 1);               allsongsarray[count] = &newsong;              free(currentsong); 

change to

memcpy(currentsong,&newsong,sizeof(newsong)); allsongsarray[count] = currentsong; 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -