I am a complete beginner. I am trying to use strtok in C to read a CSV file, and store the contents into an array structure for each column, but I have a "segmentation fault" message. I will appreciate any advice. Before this I should make a column for deaths/cases and sorting the lines in ascending order, but first I should fix this code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 200
#define COUNT 2
typedef struct data_s {
char iso[SIZE];
char continent[SIZE];
char location[SIZE];
char date[SIZE];
unsigned int cases;
unsigned int deaths;
} data_t;'
int j = 1;
int main()
{
FILE *myfile;
myfile = fopen("owid-covid-data-small.csv", "r");
if (myfile == NULL)
{
printf("Archivo no encontrado.");
}
rewind(myfile);
char myLine[SIZE];
char *delimiter = ",";
char buffer[SIZE];
memset(buffer, 0, sizeof(buffer));
int i = 0;
for (char c = getc(myfile); c != EOF; c = getc(myfile))
{
if (c == '\n')
{
j++;
}
}
data_t temp_data[j];
memset(&temp_data, 0, j*sizeof(data_t));
rewind(myfile);
while (fgets(myLine, 200, (FILE*)myfile) != NULL && i<j)
{
strcpy(temp_data[i].iso, strtok(myLine, delimiter));
strcpy(temp_data[i].continent, strtok(myLine, delimiter));
strcpy(temp_data[i].location, strtok(myLine, delimiter));
strcpy(temp_data[i].date, strtok(myLine, delimiter));
temp_data[i].cases = atoi(strtok(NULL, delimiter));
strncpy(buffer, strtok(NULL, delimiter), SIZE);
temp_data[i].deaths = atoi(buffer);
memset(buffer, 0, sizeof(buffer));
i++;
for (int i = 0; i < COUNT; i++)
{
printf("Country: %s\n", temp_data[i].location);
printf("Continent: %s\n", temp_data[i].continent);
printf("Date: %s\n", temp_data[i].date);
printf("Total cases: %u\n", temp_data[i].cases);
printf("Total deaths: %u\n", temp_data[i].deaths);
printf("\n");
}
memset(&temp_data, 0, sizeof(data_t));
}
fclose(myfile);
}