After defining file * FP, fopen is used as: fp = fopen (filename, "W "). For fopen_s, another variable errno_t err must be defined, and err = fopen_s (& FP, filename, "W") must be defined "). For fopen, if the file is successfully opened, the file pointer (assigned to FP) is returned. If the file fails to be opened, the null value is returned. For fopen_s, 0 is returned if the file is successfully opened, A non-0 error is returned.
In vs programming, the following warning is often reported: Warning c4996: 'fopen': This function or variable may be unsafe. consider using fopen_s instead. to disable deprecation, use_crt_secure_no_warnings. see online help for details. because fopen_s has more overflow detection than fopen, it is safer. (There will be a comparison between get and get_s in future articles. The comparison between strcpy strcpy_s and their commonalities are all used for unpredictable behaviors and will be explained in detail later)
#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 );}
Original article: http://blog.163.com/?email protected]/blog/static/1704104522011111452835960/
Comparison between fopen and fopen_s [zz]