I'm trying to read in a CSV file line by line and then split the lines into their values as read from the CSV file by separating the lines with the comma delimiter. Once successful, the goal is to read this 2D array into a sophisticated model in C as the input. For this I'm using getline()
and strtok()
.
I'm new to C, and I've spent weeks getting to this point so please don't suggest different functions for this unless absolutely necessary. I'll post what I have so far and insert what warnings I'm getting and where if anyone could please help me figure out why this code won't produce the array. I think it may just be a pointer issue but I've been trying everything I can and it's not working.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARRAYLENGTH 9
#define ARRAYWIDTH 7
float data[ARRAYLENGTH][ARRAYWIDTH];
int main(void) {
char *line = NULL;
size_t len = 0;
ssize_t read;
FILE *fp;
fp=fopen("airvariablesSend.csv", "r");
if(fp == NULL){
printf("cannot open file\n\n");
return -1;
}
int k , l;
char **token; //for parsing through line using strtok()
char comma = ',';
const char *SEARCH = , //delimiter for csv
char *todata;
for (l=0; l< ARRAYLENGTH +1; l++){
while ((read = getline(&line, &len, fp)) != -1) {
//Getline() automatically resizes when you set pointer to NULL and
//len to 0 before you loop
//Here, the delimiting character is the newline character in this
//form. Newline character included in csv file
//printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
//The first line prints fine here. Now once I try to parse through
//I start getting warnings:
for(k = 0; k < ARRAYWIDTH; k++) { //repeats for max number of columns
token = &line;
while (strtok(token, SEARCH)){
//I'm getting this warning for the while loop line:
//warning: passing argument 1 of `strtok' from incompatible pointer type
fscanf(&todata, "%f", token);
//I'm getting these warnings for fscanf. I'm doing this because
//my final values in the array to be floats to put in the
//model
//warning: passing argument 1 of `fscanf' from incompatible pointer type
//warning: format `%f' expects type `float *', but argument 3 has type
// 'char **'
todata = &data[l][k];
//And finally, I'm getting this warning telling me everything is
//incompatible.
//warning: assignment from incompatible pointer type.
printf("%f", data[l][k]);
}
}
}
}
free(line);
//Free memory allocated by getline()
fclose(fp);
//Close the file.
exit(EXIT_SUCCESS);
return 0;
}