我正在使用以下文本文件:https://mega.nz/#!EN4iRJxA!VtKFEl9dlQHWHIzcgfOfpXTt9_ill_YkgsLWL3nORLg 以及以下代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
char lastname[25];
char name[20];
float average;
}student;
int main(){
int i;
student *pointer= (student*) malloc(3);
FILE *file= fopen("Struct.txt", "r");
fread(pointer, sizeof(student), 3, file);
for(i= 0; i< 3; i++){
printf("Id: %d\nName: %s\nLast name: %s\nAverage: %.2f\n",
(pointer+ i) -> id,
(pointer+ i) -> name,
(pointer+ i) -> lastname,
(pointer+ i) -> average);
}
fclose(file);
system("pause");
return 0;
}
当我删除 fclose 函数时它起作用了,但我检查了一下它似乎是正确的。我错过了什么?
最佳答案
这与您的fclose
无关,相反您需要解决两件事:
需要检查
fopen
的返回错误:if( NULL == file ) { printf( "Cannot open\n" ); exit( 1 ); }
您的 malloc 代码看起来不正确,应该是:
student *pointer= malloc(3 * sizeof(student));
关于c - 程序因 fclose 而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33716575/