[英]Scanning file into an array of structures in C
My program isn't reading past the first line of my file. 我的程序没有读过我文件的第一行。 I have the file
我有文件
John 22 67
Rickard 31 100
Andrew 21 34
Sarah 20 80
Attempting to read with: 试图阅读:
void loadPeople(char fileName[],Person people[],int * length){
FILE *fptr = fopen("fileName", "r");
int i;
for(i=0; i<N; i++){
fscanf(fptr, "%s", people[i].name);
fscanf(fptr, "%d", &people[i].age);
fscanf(fptr, "%lf", &people[i].score);
fclose(fptr);
}
return;
}
The program is only reading the first line of the file into person[0] and not beyond. 该程序只是将文件的第一行读入person [0]而不是超出。
You are closing the file after reading the first record. 您正在读取第一条记录后关闭该文件。 Move
fclose()
out of the loop. 将
fclose()
移出循环。
You should also check that the file was opened successfully, by checking that fptr
is not NULL
before looping through the file. 您还应通过在循环文件之前检查
fptr
是否为NULL
来检查文件是否已成功打开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.