I'm in trouble with reading a data from a csv-file and parsing it into a struct. I think its best to show some code.
This is my struct:
typedef struct MyStruct{
char text[150];
char attr[4][50];
char check;
short int num;
} t_mystruct;
A sample line in my file could look like this: This is a long text;brown;green;yellow;silent;X;13;
Now I want to read that file and add that data to an array:
list = malloc(sizeof(t_mystruct) * LIST_SIZE); /* Allocating Memory */
for (i = 0; i < LIST_SIZE; i++) /* Adding data to list */
{
t_mystruct element;
if (fscanf(fp, "%149[^;];%49[^;];%49[^;];%49[^;];%49[^;];%49[^;];%[^;];%d;", &element.text, &element.attr[0], &element.attr[1], &element.attr[2], &element.attr[3], &element.check, &element.num) != 7)
break; /* Break ==> Incomplete line/data */
list[i] = element; /* Add to list */
}
This works, but I face two problems:
But I can't see my mistakes.
You have specified five format specifiers of
%49[^;];
but your struct has only four, and you only provide four arguments to match. You are also reading the last value as int
, when it is short
.