다음 코드를보고하십시오 : 실행하는 동안fclose()가 실패하는 이유는 무엇입니까?
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
void main() {
struct stat file_st;
int size=0, ret=0;
char* buf=NULL;
FILE* file = fopen("newfile", "r");
if (file==NULL) {
printf("error");
exit(1);
}
if (stat("newfile", &file_st)!=0) {
printf("stat failed\n");
exit(1);
}
buf = (char*)malloc(sizeof(file_st.st_size+1));
buf[file_st.st_size]='\0';
ret = fread(buf, 1, file_st.st_size, file);
printf("fread return value is: %d\n");
ret = fclose(file);
printf("fclose return value: %d\n", ret);
printf("%s\n", buf);
}
이 코드는 컴파일을 통과하지만, 충돌합니다. 왜 그런지 알아?
그러나 fclose()와 printf() (코드의 마지막 두 줄) 사이를 전환하면 코드가 성공적으로 실행되고 "newfile"의 내용이 인쇄됩니다. 이 두 가지 경우의 차이점은 무엇입니까?
'fopen '의 반환 값을 확인하지 않으시겠습니까 –
'void main'이 잘못되었습니다. – melpomene
또한'fstat (fileno (file), file_st);를 사용한다. ' –