I am trying to save csv data in an array for use in other functions. I understand that strdup is good for this, but am unsure how to make it work for my situation. Any help is appreciated!
The data is stored in a struct:
typedef struct current{
char **data;
}CurrentData;
Function call:
int main(void){
int totalProducts = 0;
CurrentData *AllCurrentData = { '\0' };
FILE *current = fopen("C:\\User\\myfile.csv", "r");
if (current == NULL){
puts("current file data not found");
}
else{
totalProducts = getCurrentData(current, &AllCurrentData);
}
fclose(current);
return 0;
}
How I allocated memory;
int getCurrentData(FILE *current, CurrentData **AllCurrentData){
*AllCurrentData = malloc(totalProducts * sizeof(CurrentData));
/*allocate struct data memory*/
while ((next = fgetc(current)) != EOF){
if (next == '\n'){
(*AllCurrentData)[newLineCount].data = malloc(colCount * sizeof(char*));
newLineCount++;
}
}
newLineCount = 0;
rewind(current);
while ((next = fgetc(current)) != EOF && newLineCount <= totalProducts){
if (ch != '\0'){
buffer[i] = ch;
i++;
characterCount++;
}
if (ch == ',' && next != ' ' || ch == '\n' && ch != EOF){
if (i > 0){
buffer[i - 1] = '\0';
}
length = strlen(buffer);
/*(*AllCurrentData)[newLineCount].data[tabCount] = malloc(length + 1); /* originally was using strcpy */
strcpy((*AllCurrentData)[newLineCount].data[tabCount], buffer);
*/
(*AllCurrentData)[newLineCount].data[tabCount] = strdup(buffer); /* something like this? */
i = 0;
tabCount++;
for (j = 0; j < BUFFER_SIZE; j++){
buffer[j] = '\0';
}
}
You define a ptr
AllCurrentData
but you should set it to NULL.CurrentData* AllCurrentData = NULL;
In
getCurrentData
you usetotalProducts
which seems a bit odd since it is a local variable in main(), either you have another global variable with the same name or there is an error.The
**data
inside the structure seems odd, instead maybe you want to parse the csv line and create proper members for them. You already have an array of CurrentData so it seems odd to have another array inside the struct -- i am just guessing cause you haven't explained that part.Since a csv file is line based use fgets() to read one line from the file, then parse the string by using e.g. strtok or just by checking the buffer after delimiters. Here strdup can come into play, when you have taken out a token, do a strdup on it and store it in your structure.
Instead of allocating a big buffer that may be enough (or not) use realloc to increase your buffer as you read from the file.
That said there are faster ways to extract data from a csv-file e.g. you can read in the whole file with fread, then look for delimiters and set these to \0 and create an array of char pointers into the buffer.