I have a text file and each line contains person name and gender in comma separated value. I am trying to read line by line and create the array of person. Not sure what went wrong with my code all the elements of the array is set to the last line of text file. (If the last line has Sam, Male, all the elements of the person array is set to Name=Sam)
struct Person{
char* Name;
char* Gender;
};
struct Person person[100];
void readAllFromFile(){
FILE * fp;
char currentLine[256];
int fd;
if((fp = fopen ("test.txt", "r"))==NULL){
perror("Can not open");
fclose(fp);
return;
}
int currentLineNo=0;
char *items;
while (fgets(currentLine, sizeof(currentLine), fp)) {
items=strtok(currentLine,",");
struct Person tempPerson;
int iter=0;
while(items != NULL)
{
if(iter==0){
tempPerson.Name=items;
}
else {
tempPerson.Gender=items;
}
iter++;
items=strtok(NULL,",");
}
person[currentLineNo]=tempPerson;
currentLineNo++;
}
/*Printing element of the array*/
int i;
for(i=0;i<currentLineNo;i++){
printf("%s\n",person[i].Name);
}
fclose(fp);
}
int main() {
readAllFromFile();
return 0;
}
The name of each person is located in the same place in memory:
currentLine. You assign that address to everyPersonsName, so every name will be displayed the same. Similar thing for eachGender.Note that, because
currentLineis local toreadAllFromFile, once that function returns, that space may be used for other things, trashing the oneNameyou managed to retain.Each
Personneeds its own allocation of space for itsNameandGender.