#include <stdio.h>
void main( void )
{
FILE *pFile=fopen("1.txt","r");
fclose(pFile);
}
这样的一段代码,理论上似乎是对的,但是相信我,你运n次就会有n次的错误,access voliation,每次都是这个错误码。
然后我对他进行一个小修改,把【FILE *pFile=fopen("1.txt","r");】里的read属性换成write【FILE *pFile=fopen("1.txt","w");】,这样你就会发现完全没问题,执行成功。
然后,怪事发生了,现在我再把【FILE *pFile=fopen("1.txt","r");】改回来,然后运行,结果成功了!
是不是很奇怪,接下来,不管你怎么使用fclose函数都不会出现上面的错误,这实在是令人费解。
想了一会终于知道是怎么回事了,在第一次以read模式打开文件的时候,由于本来不存在那个文件,fopen函数失败,所以返回NULL指针,在调用fclose的时候,由于是NULL指针,引用空地址出错,以下是fclose在vc下的实现方式:
int __cdecl fclose (
FILE *str
)
{
REG1 FILE *stream;
REG2 int result = EOF;
/* Init near stream pointer */
stream = str;
if (stream->_flag & _IOSTRG) { |
//看这,每次程序到这里就会产生异常,就是因为空地址引用 |
stream->_flag = 0;
return(EOF);
}
#endif /* _MT */
_ASSERTE(str != NULL);
if (inuse(stream)) {
/* Stream is in use:
(1) flush stream
(2) free the buffer
(3) close the file
(4) delete the file if temporary
*/
result = _flush(stream);
_freebuf(stream);
if (_close(_fileno(stream)) < 0)
result = EOF;
else if ( stream->_tmpfname != NULL ) {
/*
* temporary file (i.e., one created by tmpfile()
* call). delete, if necessary (don't have to on
* Windows NT because it was done by the system when
* the handle was closed). also, free up the heap
* block holding the pathname.
*/
#if defined (_M_MPPC) || defined (_M_M68K)
if ( _unlink(stream->_tmpfname) )
result = EOF;
#endif /* defined (_M_MPPC) || defined (_M_M68K) */
_free_crt(stream->_tmpfname);
stream->_tmpfname = NULL;
}
}
stream->_flag = 0;
return(result);
}
所以第二次在使用了write模式后,文件被创建,之后再使用read模式,fopen返回FILE*指针,当然非空,就正确了。
但是要说明一点,fclose函数在tc中的实现方式显然是不同的,你给它传一个NULL指针,它也照运不误。
注意:所以,以后再vc中调用fclose函数之前,一定要先检查FILE*时候为NULL,再行调用,否则,肯定会死的很惨….