我有一个文本文件,每一行都包含逗号分隔值的人名和性别。我正在尝试逐行阅读并创建人员数组。不确定我的代码出了什么问题,数组的所有元素都设置为文本文件的最后一行。(如果最后一行有Sam,Male,则person数组的所有元素都设置为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;
}