Here I have a C program that is supposed to pass structs that it reads from a .csv file to get the fields for the individual structs. Then it should pass the filled struct into the array. But it's not putting the information in the right slots in the array. I'm pretty new to C. I generally work with C#. So I'm not used to pointers and addresses and the like. I might have done something wrong there. If someone can point me in the right direction that would be great!
Thanks!
Code:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
typedef struct {
//COUNTRY ID, COUNTRY NAME, POPULATION, LIFE EXPECTANCY, AND DATE OF FOUNDING
char *id;
char *name;
int population;
float lifeExpectancy;
int year;
}CountryData;
CountryData FormatData(char *data);
int main()
{
int fr = open("SampleCountriesInput.csv", O_RDONLY);
int inputSize = 200;
int i = 0;
int j = 0;
char line[inputSize];
char buff[1];
ssize_t n;
CountryData countries[50];
CountryData country;
do
{
n = read(fr,buff,1);
if(buff[0] == '\n')
{
country = FormatData(line);
//countries[j] = FormatData(line);
strncpy(&countries[j].id, &country.id,3);
strncpy(&countries[j].name, &country.name, 18);
countries[j].population = country.population;
countries[j].year = country.year;
countries[j].lifeExpectancy = country.lifeExpectancy;
j++;
i=0;
}
else
line[i] = buff[0];
i++;
}while( n != 0);
j--;
while(j!=0)
{
printf(countries[j].name);
j--;
}
return 0;
}
CountryData FormatData(char *data)
{
CountryData country;
char *token[20];
int j, i = 0;
token[0] = strtok(data, ",");
while(token[i] != NULL)
{
i++;
token[i] = strtok(NULL, ",");
}
country.id = token[1];
country.name = token[2];
country.lifeExpectancy = atof(token[8]);
country.population = atoi(token[7]);
country.year = atoi(token[6]);
return country;
}