该文件是一个.bin文件。当调用终端中的函数时,程序打开文件并出现分段故障。我是否混淆了其中一种类型,或者可能没有正确使用指针?非常感谢您的帮助,谢谢您看
int main(int argc, char *argv[])
{
Student bank[20];
FILE * rfile;
Student *pStudent;
int i=0, n, end, count=0;
float graded;
char *stufile, name[256];
if (argc < 2)
{
stufile = (char *)malloc(MAX_NAME+1);
printf("What file would you like to open? ");
scanf("%s", stufile);
if (stufile ==NULL) return 1;
}
else{
stufile = argv[1];
}
// open file
rfile = fopen(stufile,"rb");
if (rfile == NULL){
printf("File not foundn");
return 1;
}
else{
printf("nn%-20s %-10s %10sn","Name", "E-mail", "Grade");
printf("------------------------------------------n");
fseek(rfile, 0, SEEK_END);
end = ftell(rfile); // will get to the EOF returning a int
fseek(rfile,0,SEEK_SET); // set cursor back
// I think this is seg fault??
while(fread(&bank[i++], sizeof(Student), 1, rfile) == 1){
if(feof(rfile)) break;
++count;
}
fclose(rfile);
}
for (i=0; i<count; ++i){
// print student info
printf("%-20s, %s %-10s %d%%n", bank[i].lastName, bank[i].firstName,
bank[i].emailAddress, bank[i].grade);
n = n + bank[i].grade;
}
graded = n/count;
printf("Average Grade:tt%.2f", graded);
return 0;
}```
Good news no longer seg fault now it is printing off[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/rZKAW.png
因为您在&bank[i++]
中使用i
而没有初始化它。