Reputation: 21
I'm having some troubles passing the information of a .csv file to a struct using linked lists...
The file is like:
1,3.234,hello,f
3,4.2432,worldkind,o
.
.
.
My C Program:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 50
typedef struct TP
{
int key;
//data
int atomnum;
float massnum;
char nome[MAX+1];
char sym[MAX+1];
struct tableper *nseg;
struct tableper *nant;
}tp;
tp* putmemory(tp *dbase1) //function to put data to struct
{
FILE *fp1;
char *token,ch,temp[MAX];
int *tokenint,i,aux[MAX],in=-1,flag=0;
char BUFFER[MAX],*aux2;
tp *nv;
if ((fp1 = fopen("TabelaPeriodica.csv","r")) == NULL)
printf("File could not be opened \n");
while(!feof(fp1))
{
while((ch=fgetc(fp1)) != '\r')
{
temp[++in]=ch;
if(ch == ',')
{
nv->key = ++i;
token = strtok(temp[++i],",");
nv->atomnum = token;
token = strtok(NULL,",");
nv->massnum = atof(token);
token = strtok(NULL,",");
strcpy(nv->nome,token);
token = strtok(NULL,",");
strcpy(nv->sym,token);
free(nv);
}
}
}
}
int main()
{
tp *dbase1;
putmemory(dbase1);
return 0;
}
My problems are:
Upvotes: 1
Views: 972
Reputation: 108938
You need to allocate memory for nv
.
In your current code, nv
is an uninitialized pointer. You can't use it just like that.
Also you have a free(nv)
in your code and no corresponding nv = malloc(sizeof *nv);
or similar
Upvotes: 1
Reputation: 4859
one of the many issues I spot is that you never allocate memory for nv
...
Also I would use fgets
to read a whole line and then use strtok
on it
again, you have to allocate nv
, and then set dbase1
to it, so you build up a linked list
Upvotes: 1