fopen与fopen_s的区别

来源:互联网 发布:贵州广电网络怎么缴费 编辑:程序博客网 时间:2024/04/30 11:50

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多了溢出检测,更安全一些。(在以后的文章里还有get与get_s的比较,strcpy strcpy_s的比较,他们的共同点都是用来一些不可预料的行为)#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" );

 "wb+"  以二进制模式打开文件

 

"w+"     以文本模式打开文件

open_s的安全是在于比函数fopen多了溢出检测。另外在使用上,函数fopen的返回值是文件指针,如果返回的文件指针为NULL时,则表示打开文件失败。而函数fopen_s的返回值是相应的错误代码,通过查看错误代码代表的含义,有助于你排查问题。还有一点,fopen_s打开的文件不能共享,如果你打开的文件需要共享的话,不能使用fopen_s函数。可以考虑_fsopen,_wfsopen这两个函数。



0 0
原创粉丝点击