Reputation: 11
How could I fix my code that populates two separate arrays from a CSV file that contains words separated by semicolons in C?
My CSV file looks something like this:
to meet/encounter;begegnen
to care for/look after;betreuen
superior;vorgesetzt
to borrow/lend/rent;ausleihen
My function:
#define LINE_SIZE 100
#define STRING_SIZE 55
char **source_vocab = NULL;
char **target_vocab = NULL;
void allocate_mem(char **dictionary, int n)
{
for(int i = 0; i < n; i++)
{
dictionary[i] = malloc(STRING_SIZE * (sizeof(char)));
if(dictionary[i] == NULL)
{
printf("%sMemory Error. Exiting..", RED);
return;
}
}
}
void populate_arrs(FILE *fptr)
{
char *line = malloc(LINE_SIZE * sizeof(char));
int count = 0;
while(fgets(line, sizeof(line), fptr) != NULL)
{
line[strcspn(line, "\n")] = 0;
char *token = strtok(line, ";");
token = strtok(line, ";");
if(token != NULL)
source_vocab[count] = strdup(token);
token = strtok(NULL, ";");
if(token != NULL)
target_vocab[count] = strdup(token);
count++;
}
}
Incorrect output that it produces:
English: to meet
German: ow/lend
English: encou
German: leihen
English: nter
German:
English: gegnen
I've tried modifying my sample CSV file and using a TXT file instead. It didn't help. The function should perfectly separate my words into two arrays, e.g.:
English: to meet/encounter
German: begegnen
Upvotes: 0
Views: 48
Reputation: 44340
Here is one problem:
while(fgets(line, sizeof(line), fptr) != NULL)
^^^^^^^^^^^^
wrong
It means "size of a char pointer". Typically 4 or 8.
It's not the size of the memory it points to.
So use LINE_SIZE
instead, i.e.
while(fgets(line, LINE_SIZE, fptr) != NULL)
BTW: sizeof(char)
is 1
by definition so you don't need to write it in your code.
Upvotes: 1