C++ 如何从 fopen 转到 fopen_s

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28691612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 21:02:10  来源:igfitidea点击:

How to go from fopen to fopen_s

c++cwindowsc11tr24731

提问by beatleman

Visual Studio is complaining about fopen. I can't find the proper syntax for changing it. I have:

Visual Studio 抱怨 fopen。我找不到更改它的正确语法。我有:

FILE *filepoint = (fopen(fileName, "r"));

to

FILE *filepoint = (fopen_s(&,fileName, "r"));

What is the rest of the first parameter?

第一个参数的其余部分是什么?

回答by chqrlie

fopen_sis a "secure"variant of fopenwith a few extra options for the mode string and a different method for returning the stream pointer and the error code. It was invented by Microsoft and made its way into the C Standard: it is documented in annex K.3.5.2.2 of the most recent draft of the C11 Standard. Of course it is fully documented in the Microsoft online help. You do not seem to understand the concept of passing a pointer to an output variable in C. In your example, you should pass the address of filepointas the first argument:

fopen_s是一种“安全”变体,fopen带有一些额外的模式字符串选项和一种用于返回流指针和错误代码的不同方法。它由 Microsoft 发明并进入 C 标准:它记录在 C11 标准最新草案的附件 K.3.5.2.2 中。当然,它在 Microsoft 联机帮助中有完整记录。您似乎不明白在 C 中传递指向输出变量的指针的概念。在您的示例中,您应该将 的地址filepoint作为第一个参数传递:

errno_t err = fopen_s(&filepoint, fileName, "r");

Here is a complete example:

这是一个完整的例子:

#include <errno.h>
#include <stdio.h>
#include <string.h>
...
FILE *filepoint;
errno_t err;

if ((err = fopen_s(&filepoint, fileName, "r")) != 0) {
    // File could not be opened. filepoint was set to NULL
    // error code is returned in err.
    // error message can be retrieved with strerror(err);
    fprintf(stderr, "cannot open file '%s': %s\n",
            fileName, strerror(err));
    // If your environment insists on using so called secure
    // functions, use this instead:
    char buf[strerrorlen_s(err) + 1];
    strerror_s(buf, sizeof buf, err);
    fprintf_s(stderr, "cannot open file '%s': %s\n",
              fileName, buf);
} else {
    // File was opened, filepoint can be used to read the stream.
}

Microsoft's support for C99 is clunky and incomplete. Visual Studio produces warnings for valid code, forcing the use of standard but optional extensions but in this particular case does not seem to support strerrorlen_s. Refer to Missing C11 strerrorlen_s function under MSVC 2017for more information.

Microsoft 对 C99 的支持笨拙且不完整。Visual Studio 为有效代码生成警告,强制使用标准但可选的扩展,但在这种特殊情况下似乎不支持strerrorlen_s. 有关详细信息,请参阅MSVC 2017 下的 Missing C11 strerrorlen_s 函数