I'm programming a simple program to implement a linked list using the programming language C.
The elements to be added in the list are given in a CSV-File.
I want each line to be safed in a struct. Which I can then add to the list.
The CSV-File looks like this:
datatype1;datatype2;datatype3;datatype4;datatype5;datatype6
there are some special chars in it.
My attempt now to read from the csv and safe it line by line in a struct looks like this:
void createListFromCSV(char *path_csv, struct listenElement **list)
{
FILE *CSV = fopen(path_csv, "r");
if (CSV == NULL)
{
exit(-1);
}
//datatype1;datatype2;datatype3;datatype4;datatype5;datatype6
//%s,%s,%s,%s,%s,%s
char read[150];
const char delimiter[2] = ";";
fgets(read, 150, CSV);
while (!feof(CSV))
{
int counter = 0;
dataElement newElement;
char *token = strtok(read, delimiter);
while (token != NULL)
{
switch (counter)
{
case 0:
strcpy(newElement.datatype1, token);
break;
case 1:
strcpy(newElement.datatype2, token);
break;
case 2:
strcpy(newElement.datatype3, token);
break;
case 3:
strcpy(newElement.datatype4, token);
break;
case 4:
strcpy(newElement.datatype5, token);
break;
case 5:
strcpy(newElement.datatype6, token);
break;
default:
printf("%s\n", "[!!] Error unknown part of the string");
break;
}
counter++;
token = strtok(NULL, delimiter);
}
fgets(read, 150, CSV);
putOnEndOfList(list, &newElement);
}
// delete the first Element of the list!
deleteElement(list, "datatype5");
fclose(CSV);
}
There have to be a much better way to read from the CSV and I researched, but nothing really worked for me in this example.
NOTICE: the datatypes also have some special chars !
This attempt works, but it is not working for other CSV-Files and is really unusable.
I would appreciate some suggestion for a better solution :)
I'm not searching for a library. I want to implement it myself