c++中fopen和fopen_s比較
FILE * fopen(const char * path,const char * mode);接收兩個實參
返回值:文件順利打開後,指向該流的文件指針就會被返回。如果文件打開失敗則返回NULL,並把錯誤代碼存在errno 中。
errno_t fopen_s( FILE** pFile, const char *filename, const char *mode );
pFile:文件指針將接收到打開的文件指針指向的指針。filename:文件名。mode:訪問類型。
返回值:如果成功返回0,失敗則返回相應的錯誤代碼。
建議用fopen_s,比fopen多了溢出檢測,更安全一些。
#include <stdio.h>
FILE *stream, *stream2;
int main( void )
{
int numclosed;
errno_t err;
// Open for read (will fail if file "crt_fopen_s.c" does not exist)
if( (err = fopen_s( &stream, "crt_fopen_s.c", "r" )) !=0 )
printf( "The file 'crt_fopen_s.c' was not opened\n" );
else
printf( "The file 'crt_fopen_s.c' was opened\n" );
// Open for write
if( (err = fopen_s( &stream2, "data2", "w+" )) != 0 )
printf( "The file 'data2' was not opened\n" );
else
printf( "The file 'data2' was opened\n" );
// Close stream if it is not NULL
if( stream)
{
if ( fclose( stream ) )
{
printf( "The file 'crt_fopen_s.c' was not closed\n" );
}
}
// All other files are closed:
numclosed = _fcloseall( );
printf( "Number of files closed by _fcloseall: %u\n", numclosed );
}