• fopen和fopen_s的区别


    转载:https://blog.csdn.net/keith_bb/article/details/50063075

    fopen:

    原型:FILE * fopen(const char * path,const char * mode);接收两个实参

    返回值:文件顺利打开后,指向该流的文件指针就会被返回。如果文件打开失败则返回NULL,并把错误代码存在errno 中。

    示例程序源码:FILE *cfPtr;

                             if((cfPtr = fopen("test.dat","w")) == NULL)   //若cfPtr = NULL,即文件未成功打开,函数返回0,否则返回1

                                       return 0;

                             else   return 1;

    fopen_s:

    原型:

    errno_t fopen_s( FILE** pFile, const char *filename, const char *mode );
    errno_t _wfopen_s( FILE** pFile, const wchar_t *filename, const wchar_t *mode );
    pFile:文件指针将接收到打开的文件指针指向的指针。infilename:文件名。inmode:允许的访问类型。
    返回值:如果成功返回0,失败则返回相应的错误代码。

    示例程序源码:(转载自:百度百科)

    #include<stdio.h>
     
    FILE*stream,*stream2;
     
    intmain(void)
     
    {
     
    errno_terr;
     
    //Openforread(willfailiffile"crt_fopen_s.c"doesnotexist)
     
    err=fopen_s(&stream,"crt_fopen_s.c","r");
     
    if(err==0)
     
    {
     
    printf("Thefile'crt_fopen_s.c'wasopened ");
     
    }
     
    else
     
    {
     
    printf("Thefile'crt_fopen_s.c'wasnotopened ");
     
    }
     
     
     
    //Openforwrite
     
    err=fopen_s(&stream2,"data2","w+");
     
    if(err==0)
     
    {
     
    printf("Thefile'data2'wasopened ");
     
    }
     
    else
     
    {
     
    printf("Thefile'data2'wasnotopened ");
     
    }
     
    //ClosestreamifitisnotNULL
     
    if(stream)
     
    {
     
    err=fclose(stream);
     
    if(err==0)
     
    {
     
    printf("Thefile'crt_fopen_s.c'wasclosed ");
     
    }
     
    else
     
    {
     
    printf("Thefile'crt_fopen_s.c'wasnotclosed ");
     
    }
     
    }
     
    //Allotherfilesareclosed:
     
    intnumclosed=_fcloseall();
     
    printf("Numberoffilesclosedby_fcloseall:%u ",numclosed);
     
    }

  • 相关阅读:
    10月9日学习日志
    10月2日学习日志
    11月3日学习日志
    10月5日学习日志
    10月6日学习日志
    10月7日学习日志
    11月4日学习日志
    AccessDatabaseEngine.exe 32位64安装失败问题
    国产各安卓系统接收消息在杀进程后
    SAP容差组
  • 原文地址:https://www.cnblogs.com/MCSFX/p/12658261.html
Copyright © 2020-2023  润新知