有关scanf_s、fopen_s等CRT安全函数 fopen函数

scanf_s、fopen_s等函数是与scanf、fopen等函数对应的安全版本,(fopen、scanf等函数的使用存在安全风险),这是微软对C/C++语言的扩展,是微软特有的(Microsoft-specific),不属于ANSI标准。
有关scanf_s、fopen_s等CRT安全函数 fopen函数
这类函数还包括get_s,printf_s,sscanf_s,... 等等[参看常用的安全CRT函数或这里]其中,scanf_s和fopen_s的原型如下:int scanf_s( const char *format [, argument]...);//<stdio.h>errno_t fopen_s( FILE** pFile, const char *filename, constchar *mode ); // <stdio.h>
若干CRT安全函数原型用到的数据类型的定义:#include <crtdefs.h>typedefint errno_t;typedefunsigned short wchar_t;#ifdef _WIN64typedefunsigned __int64 size_t;#elsetypedef_W64 unsigned int size_t;#endif

------------------------------------------下面cplusplus.com上有人给出的对scanf_s函数在非微软环境下的类似做法[来源]:
/ *注解:Any format string of the form "%s" is dangerous because itdoesn't prevent buffer overflow (a security concern). For all suchfunctions MS introduced 'secure' versions, like scanf_s().But plain-old scanf() is the ANSI standard, and it is notdeprecated by anyone but MS.Just make sure there is always a number between % and s inyour format strings.* /
#ifndef _MSC_VER#define scanf_s( fmt, ...) scanf( scanf_validate( fmt, __FILE__, __LINE__ ), __VA_ARGS__)const char*scanf_validate( const char* fmt, const char* file, long line){ constchar* p = fmt; while(1) { p = strstr( p, "%s" ); if (p == NULL) break; if ((p == fmt) || (*(p-1) != '%')){ fprintf(stderr, "Hey, you used "%%s" in %s: line %d!n", file, line); abort(); } } returnfmt;}#endif

  

爱华网本文地址 » http://www.413yy.cn/a/25101013/187082.html

更多阅读

声明:《有关scanf_s、fopen_s等CRT安全函数 fopen函数》为网友莫浅苏分享!如侵犯到您的合法权益请联系我们删除