I am going to take data from csv file but when I use strtok function to split the data by comma separation here when I put splitted strings in array . It couldn't show real output
#include <stdio.h>
#include <string.h>
int i = 0;
int j = 0;
char *name[20];
int main() {
FILE *fp = fopen("meetingData.csv", "r");
if (!fp)
printf("Can't open file\n");
else {
int count;
char buffer[1024];
while (fgets(buffer,1024, fp)) {
char *value = strtok(buffer, ", ");
printf("%s\n",value);
int x = 0;
while (value != NULL) {
if (x == 0) {
name[i] = value;
printf("name[%d]is %s", i, name[i]);
i = i 1;
x ;
} else if (x == 1) {
printf("\n");
x ;
} else {
//time[j] = j '0';
// printf("%s",value);
//printf("%d\n",x);
x ;
j ;
}
value = strtok(NULL, ",");
// printf("%d\n", x);
}
}
for (int k = 0; k < count; k ) {
printf("%s\n", name[k]);
// printf("%s\n", time[k]);
}
fclose(fp);
}
return 0;
}
Here you can see my outputs they show the data with array
but when I print in a loop the last element will print for whole array index
/home/karan/untitled14/cmake-build-debug/untitled14
Ashley_Parry
name[0]is Ashley_Parry
Namal_Perera
name[1]is Namal_Perera
Namal_Perera
name[2]is Namal_Perera
Prabath_Silva
name[3]is Prabath_Silva
Bethany_William
name[4]is Bethany_William
Ashley_Parry
name[5]is Ashley_Parry
Namal_Perera
name[6]is Namal_Perera
Aaliya_Bruce
name[7]is Aaliya_Bruce
Aaliya_Bruce
name[8]is Aaliya_Bruce
Prabath_Silva
name[9]is Prabath_Silva
Waruni_Fernando
name[10]is Waruni_Fernando
Raul_Oliver
name[11]is Raul_Oliver
Aaliya_Bruce
name[12]is Aaliya_Bruce
Dr_Rajitha_Karunarathna
name[13]is Dr_Rajitha_Karunarathna
Raul_Oliver
name[14]is Raul_Oliver
Jasper_Jensen
name[15]is Jasper_Jensen
Jasper_Jensen
name[16]is Jasper_Jensen
Namal_Perera
name[17]is Namal_Perera
Chamira_Perera
name[18]is Chamira_Perera
Wasana_Tennekoon
name[19]is Wasana_Tennekoon
Dr_Kamal_Jayasooriya
name[20]is Dr_Kamal_Jayasooriya
Raul_Oliver
name[21]is Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
Raul_Oliver
CodePudding user response:
strtok
does not allocate any memory, it just returns pointers into the memory you use. In here you have one single buffer
into which you read data and then tokenize it. This means every time the first item returned the pointer is the same as buffer
and every time you read new data it overwrites the old.
You’ll need to allocate memory for the data you want to store (perhaps with strdup
) and then manage freeing it when not needed.