I'm trying to read a CSV file in C and store that data into a vector.
My CSV file entries for each line looks like: 12/12/1914, 52.4
, however, I am only interested in retrieving the number from this CSV, not the dates.
To accomplish this, I've been trying to read the file line by line using fgets()
, and then separating the number value out through the use of strtok()
.
When I print out the results of strtok()
I get the numbers I am looking for, but I also get (null)
printed with them:
(null)
25798.42
(null)
25706.68
(null)
25379.45
(null)
25444.34
(null)
25317.41
Also, when I try and print the actual vector entires, they just print out garbage (I assume this is because (null)
is attached to them but not positive):
3907216808; 0;
3907216808; 0;
My function for reading the data looks like this:
void get_CSV_data(vc_vector* prices)
{
FILE *fp = fopen(_FILE_PATH, "r");
char singleLine[20];
while(!feof(fp)){
fgets(singleLine, 20, fp);
char* token = strtok(singleLine, ",");
while (token != NULL) {
token = strtok(NULL, ",");
printf("%s\n", token);
vc_vector_push_back(prices, &token);
}
}
// Print each vector element
for (void* i = vc_vector_begin(prices);
i != vc_vector_end(prices);
i = vc_vector_next(prices, i)) {
printf("%u; ", *(int*)i);
}
}
I assume I am using strtok()
incorrectly, can anyone advise?
Also, while I am here, quick side question, is free(token);
needed at some point? Or no because malloc()
was never called? Still pretty new to C.
EDIT: My function now looks like:
void get_CSV_data(vc_vector* prices)
{
FILE *fp = fopen(_FILE_PATH, "r");
char singleLine[20];
while(fgets(singleLine, 20, fp) != NULL){
char* token = strtok(singleLine, ",");
token = strtok(NULL, ",");
//printf("%s\n", token);
vc_vector_push_back(prices, strdup(token));
}
// Print each vector element
for (void* i = vc_vector_begin(prices);
i != vc_vector_end(prices);
i = vc_vector_next(prices, i)) {
printf("%s\n ", (char*)i);
}
}
I get results like:
25598.7425052.8325339.9925250.5525798.4225706.6825379.4525444.3425317.4125191.43 25052.8325339.9925250.5525798.4225706.6825379.4525444.3425317.4125191.43
25339.9925250.5525798.4225706.6825379.4525444.3425317.4125191.43
25250.5525798.4225706.6825379.4525444.3425317.4125191.43
25798.4225706.6825379.4525444.3425317.4125191.43
25706.6825379.4525444.3425317.4125191.43
25379.4525444.3425317.4125191.43
Which are correct.