Comparison between fopen and fopen_s [zz]

Source: Internet
Author: User

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.