file read line by line in c resetting value to last entry

102 views Asked by At

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;
  }
1

There are 1 answers

0
Scott Hunter On

The name of each person is located in the same place in memory: currentLine. You assign that address to every Persons Name, so every name will be displayed the same. Similar thing for each Gender.

Note that, because currentLine is local to readAllFromFile, once that function returns, that space may be used for other things, trashing the one Name you managed to retain.

Each Person needs its own allocation of space for its Name and Gender.