为什么结构体只保留文件的最后一行?
typedef struct Student
{
char* nume;
char* prenume;
int cod;
float nota;
}Student;
int fileNrLines(int lines)
{
FILE *fp = fopen("students.csv", "r");
char ch;
lines = 0;
lines++;
while ((ch = fgetc(fp)) != EOF)
{
if (ch == '\n')
lines++;
}
fclose(fp);
return lines;
}
void printStudents(Student *myStudents, int size)
{
for (int i = 0; i < size; ++i)
printf("| %20s | %20s | %d | %.2f |\n",
myStudents[i].nume, myStudents[i].prenume, myStudents[i].cod, myStudents[i].nota);
}
void main()
{
int lines=0;
Student *myStudents;
myStudents = (Student*)malloc(fileNrLines(lines) * sizeof(Student));
lines = fileNrLines(lines);
FILE *fp = fopen("students.csv", "r");
char myLine[50];
char* myWord;
int index = 0;
for (int i = 0; i < lines; i++)
{
fgets(myLine, 50, fp);
int contor = 1;
myWord = strtok(myLine, ",");
while (myWord!=NULL)
{
myStudents[index].nume = myWord;
//puts(myStudents[i].nume);
myWord=strtok(NULL, ",");
contor++;
myStudents[index].prenume = myWord;
//puts(myStudents[i].prenume);
myWord=strtok(NULL, ",");
contor++;
int x = atoi(myWord);
myStudents[index].cod = x;
//printf(" %d \n",myStudents[i].cod);
myWord=strtok(NULL, ",");
contor++;
float y = atoll(myWord);
myStudents[index].nota = y;
//printf(" %.2f \n", myStudents[i].nota);
myWord=strtok(NULL, ",");
contor++;
}
index++;
}
fclose(fp);
printStudents(myStudents, &lines);
}
如果我打印到 while 循环中是可以的,但之后就不行了
最佳答案
问题在于(例如这一行)
myStudents[index].nume = myWord;
不会用新的且唯一的字符串填充nume
。相反,它只是分配 myWord
当前指向的内存位置。由于这是每行上的第一个标记,因此它始终可能指向 myLine
的开头,因此每个 nume
将是相同的。对于其他列,myWord
的位置会有所不同,因此您会得到更多意想不到的结果。
相反,您希望每次都创建一个新字符串,如下所示。
myStudents[index].nume = strdup(myWord);
或者
myStudents[index].nume = malloc(strlen(myWord)+1);
strcpy(myStudents[index].nume,myWord);
您需要记住free()
已分配的内存。
关于c - 我有一个 csv 文件,我想将数据放入结构中,但我不知道为什么它只保留最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48116758/