I’m having a problem when using strtok and I don’t know if the problem is on strtok or something else.
I have a .txt file with data like this:
sometextdada;othertextdata
yetmoredata;andmoredata
The read data is to store in an struct defined this way:
typedef struct team{
char *name;
char *teamPlace;
}Team;
If I do this:
char buffer[100];
Team eq;
/*Read first line*/
fgets(buffer, 100, equipas)!= NULL);
eq.name= strtok(buffer,";\n");
eq.teamPlace= strtok (NULL,";\n");
printf("%s %s\n", eq.name,eq.teamPlace);
I can see that strtok is working as expected and storing sometextdada in eq.name and othertextdata in eq.teamPlace
Now I want to replace that printf with a function that adds eq to a linked list that’s defined this way:
typedef struct nodeTeam{
int numberOfTeams;
Team team;
struct nodeTeam *next;
struct nodeTeam *prev;
}NodeTeam;
So I replace the printf by addNodeTeamsSorted(headEquipas,&tailEquipas,eq);
fgets(buffer, 100, equipas)!= NULL);
eq.name= strtok(buffer,";\n");
eq.teamPlace= strtok (NULL,";\n");
addNodeTeamsSorted(headEquipas,&tailEquipas,eq);
Now, if I print my linked list, I can see that my node is added but name and teamPlace contains rubbish characters. But if I do this:
fgets(buffer, 100, equipas)!= NULL);
eq.name= "test";
eq.teamPlace= "test2";
addNodeTeamsSorted(headEquipas,&tailEquipas,eq);
I can see that all is working as expected so that leads me to thinking that the problem is when string the char on my struct
What am I doing wrong?
strtokoperates on the buffer you specify in the first call. Instead of storing the returned pointers directly (which points back tobuffer, that you overwrite in the processing of each line), you need to make a copy of the string (e.g.strncpy())