2.5.5 使用CRT库的安全版本
Visual C++(www.cppentry.com)为一些CRT函数提供了安全版本,即secure version,这些安全版本的函数增强了参数校验、缓冲区大小检测、格式化参数校验等功能。原先那些旧的函数在Visual C++(www.cppentry.com)中会被提示成"deprecated(不建议使用)",如图2-53所示。
|
| (点击查看大图)图2-53 不安全的CRT调用 |
负责任的程序员应该依照这些警告,改用安全的版本。比如,前面用到的函数都具有相应的的安全版本:
- errno_t fopen_s(
- FILE** pFile,
- const char *filename,
- const char *mode
- );
-
- int fprintf_s(
- FILE *stream,
- const char *format [,
- argument ]...
- );
-
- int fwprintf_s(
- FILE *stream,
- const wchar_t *format [,
- argument ]...
- );
-
- int fscanf_s(
- FILE *stream,
- const char *format [,
- argument ]...
- );
-
- int fwscanf_s(
- FILE *stream,
- const wchar_t *format [,
- argument ]...
- );
后缀_s表明该函数是一个安全版本(secure version)。
现在动手
接下来,我们体验如何采用CRT库函数的secure版本来操作文件。
【程序 2 15】使用CRT库的安全版本输出茴字
- 01 #include "stdafx.h"
- 02 #include <cstdio>
- 03
- 04 int main()
- 05 {
- 06
- 07 FILE * fp;
- 08 fopen_s(&fp, "test.out", "w");
- 09 fprintf_s(fp, "茴香豆的茴");
- 10 fclose(fp);
- 11
- 12
- 13 fopen_s(&fp, "test.out", "r");
- 14 char line[256];
- 15 fscanf_s(fp, "%s", line, 256);
- 16 printf_s("%s\r\n", line);
- 17 fclose(fp);
- 18
- 19 return 0;20 }
光盘导读
该项目对应于光盘中的目录"\ch02\ CrtSafeWriter"。
【责任编辑:
云霞 TEL:(010)68476606】