![有关scanf_s、fopen_s等CRT安全函数 fopen函数](http://img.aihuau.com/images/01111101/01023039t0161f5216d9dedb0b3.jpg)
这类函数还包括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