I've been trying to figure this one out for a while now, and I feel like I have to be close. Basically, I have a data file containing various country records separated by new lines. Each record contains comma separated fields, of which I am trying to extract certain ones.
For example (as a single line):
60,AFG,Afghanistan,Asia,Southern and Central Asia,652090,1919,22720000,45.9,5976,Afganistan/Afqanestan,Islamic Emirate,Mohammad Omar,1,AF
Each one of these lines will make up a struct. Essentially, I want to read each one of these lines and insert it into an array of struct pointers (so dynamically). I also only want specific fields. When I "tokenize" the line I want the fields for code, name, population, and life expec. respectively:
AFG, Afghanistan, 22720000, 45.
My thought was to use fgets() to read each line in the file, and in a loop malloc() some memory for the pointers, tokenize on the fields I want, then insert. However, something that I'm doing must be wrong, as various tests don't seem to show anything in my output.
Here is my work thus far. I would appreciate any and all help.
#include "allheaders.h" // contains all common headers for personal use
#define BUF_SIZE 512
#define NUM_RECS 238
typedef struct {
char code[4];
char name[40];
int population;
float lifeExpectancy;
} Country;
typedef Country *countryPtr;
int main( int argc, const char* argv[] ) {
/* Opening the file */
FILE *filePtr; // pointer to file
if ((filePtr = fopen("AllCountries.dat", "r")) == NULL) { // if couldn't open file
printf("Error opening file\n"); // error message
exit(1);
}
/* Reading the file */
char buffer[BUF_SIZE]; // buffer to read
int index = 0;
char *token;
countryPtr *myCountries = malloc(sizeof(*myCountries) * NUM_RECS);
for(int i = 0; i < NUM_RECS; ++i) {
myCountries[i] = malloc(sizeof(*myCountries[i]));
}
while (fgets(buffer, BUF_SIZE, filePtr) != NULL) {
token = strtok(buffer,",");
token = strtok(NULL, ",");
strcpy(myCountries[index]->code, token);
token = strtok(NULL, ",");
strcpy(myCountries[index]->name, token);
token = strtok(NULL, ",");
token = strtok(NULL, ",");
token = strtok(NULL, ",");
token = strtok(NULL, ",");
token = strtok(NULL, ",");
myCountries[index]->population = atoi(token);
token = strtok(NULL, ",");
myCountries[index]->lifeExpectancy = atof(token);
//printf("%s", buffer);
index++;
}
printf("%s", myCountries[1]->code); // test?
free(myCountries);
}