Hi everyone,
Just a bit of a hand with a problem thats been driving me up the wall of late if anyone would be so kind, if been set a problem of reading in 2 external csv files into my C prog and holding them both in arrays before doing various calculations on them. Ive managed to almost get the first file read in but keep getting a segmentation error, ive a pretty good idea of where its happening but try as i might i cant seem to crack it. I'll post the prog i have so far below and any help in pointing me in the right direction would be appreciated
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int year; // year for which data exists
double pop; // Population that year (in millions)
double bot;
double botPerHead;
} Data;
typedef struct {
char countryName[50]; // maximum length of name
char countryCode[4]; // UN assigned 3 character country code
Data yearlyData[11]; // max. 12 year’s data (1995 – 2006)
} Country;
int main(void)
{
FILE *fppop;
FILE *fpbot;
Country countries[250];
int i = -1;
int dataYear;
char input[1500];
char *p;
char previousName[50] = "";
// read in pop file
fppop = fopen("un-country-pop.csv", "r");
if (fppop == NULL) {
puts("Error opening file");
exit(EXIT_FAILURE);
}
while (!feof(fppop)) {
fgets(input, 1500, fppop);
if (input[0] == '#')
continue;
p = strtok (input,",");
if (strcmp(p, previousName) != 0) {
// first time we've seen this country
i++;
// copy country name to countries[i].
strcpy(previousName, p);
}
strcpy(countries[i].countryName, p);
p = strtok (NULL,",");
strcpy(countries[i].countryCode, p);
strtok(NULL,",");
strtok(NULL,",");
strtok(NULL,",");
// im pretty sure the segmentation fault is happening here as im not quite sure how to assign the year and population values to the array within an array
p = strtok(NULL,","); // year string
dataYear = atoi(p);
countries[i].yearlyData[2006 - dataYear].year = atoi(p);
//p = strtok(NULL,","); //pop
//countries[i].yearlyData[2006 - dataYear].pop = atof(p);
}
printf("%d\n",i);
}