当前位置:C++技术网 > 资讯 > fopen_s函数

fopen_s函数

更新时间:2015-11-20 23:53:32浏览次数:1+次


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 );
打开一个文件,这些版本比fopen,_wfopen在安全性上都有增强。


pFile
文件指针将接收到打开的文件指针指向的指针。
filename
文件名。
mode
允许的访问类型。
返回值:
如果成功返回0,失败则返回相应的错误代码。
错误代码请到_doserrno,errno, _sys_errlist, and _sys_nerr去了解更多
通过打开的文件fopen_s和_wfopen_s不是可共享。如果您需要先设置为可共享一个文件,则使用_fsopen、_wfsopen与适当的共享模式常量 — — 例如,_SH_DENYNO为读/写的共享。
fopen_s支持 Unicode 的文件流。若要打开新的或现有的 Unicode 文件,请传递ccs标志,它指定所需的编码为fopen_s::
fopen_s(&fp, "newfile.txt", "rw,ccs=encoding");
支持文件:
fopen_s支持 Unicode 的文件流。若要打开新的或现有的 Unicode 文件,请传递ccs标志,它指定所需的编码为fopen_s::
fopen_s(&fp, "newfile.txt", "rw,ccs=encoding");
允许的值encoding的UNICODE,UTF-8,和UTF-16LE.如果存在未指定值的encoding,fopen_s使用 ANSI 编码。
如果该文件已经存在,并且已打开以进行读取或追加,字节顺序标记 (BOM),如果存在于文件中,将确定的编码。物料清单编码优先通过编码由ccs标志。ccs没有物料清单时存在,或如果该文件是新文件只使用编码。
允许的值encoding的UNICODE,UTF-8,和UTF-16LE.如果存在未指定值的encoding,fopen_s使用 ANSI 编码。
如果该文件已经存在,并且已打开以进行读取或追加,字节顺序标记 (BOM),如果存在于文件中,将确定的编码。物料清单编码优先通过编码由ccs标志。ccs没有物料清单时存在,或如果该文件是新文件只使用编码。
具体的mode类型请百度搜索,在这里我就写出特殊的mode
ccs=ENCODING
指定编码的字符集可用于此文件 (utf-8、 UTF-16LE 和 UNICODE)。离开这未指定是否希望 ANSI 编码。
有效的字符mode中使用的字符串fopen_s和_fdopen对应于oflag参数中使用_ 打开和_sopen,如下:

代码理解:


#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\n");
}
else
{
printf("Thefile'crt_fopen_s.c'wasnotopened\n");
}
 
//Openforwrite
err=fopen_s(&stream2,"data2","w+");
if(err==0)
{
printf("Thefile'data2'wasopened\n");
}
else
{
printf("Thefile'data2'wasnotopened\n");
}
//ClosestreamifitisnotNULL
if(stream)
{
err=fclose(stream);
if(err==0)
{
printf("Thefile'crt_fopen_s.c'wasclosed\n");
}
else
{
printf("Thefile'crt_fopen_s.c'wasnotclosed\n");
}
}
//Allotherfilesareclosed:
intnumclosed=_fcloseall();
printf("Numberoffilesclosedby_fcloseall:%u\n",numclosed);
}