zoukankan      html  css  js  c++  java
  • fopen和fopen_s用法的比较

    参考:

    在定义FILE * fp 之后,fopen的用法是: fp = fopen(filename,"w")。而对于fopen_s来说,还得定义另外一个变量errno_t err,然后err = fopen_s(&fp,filename,"w")。返回值的话,对于fopen来说,打开文件成功的话返回文件指针(赋值给fp),打开失败则返回NULL值;对于fopen_s来说,打开文件成功返回0,失败返回非0。

    在vs编程中,经常会有这样的警告: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.  是因为  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 " );    else       printf( "The file 'crt_fopen_s.c' was opened " );

       // Open for write     if( (err = fopen_s( &stream2, "data2", "w+" )) != 0 )       printf( "The file 'data2' was not opened " );    else       printf( "The file 'data2' was opened " );

       // Close stream if it is not NULL     if( stream)    {       if ( fclose( stream ) )       {          printf( "The file 'crt_fopen_s.c' was not closed " );       }    }

       // All other files are closed:    numclosed = _fcloseall( );    printf( "Number of files closed by _fcloseall: %u ", numclosed ); }

  • 相关阅读:
    matlab练习程序(RGB2HSV、HSV2RGB)
    matlab练习程序(距离变换)
    C++生成xml(使用tinyxml)
    matlab练习程序(RGB2YUV、YUV2RGB)
    修改 Google Desktop 的缓存目录
    Access 2003 中 null 和 '' 空字符串的奇怪问题
    娃娃
    【js:片断】jQuery 设置 select 下拉框的选中状态
    由 TypeInitializationException 引起的问题
    afaca 分析报告
  • 原文地址:https://www.cnblogs.com/MCSFX/p/11099173.html
Copyright © 2011-2022 走看看