如何从fopen转到fopen_s

bea*_*man 15 c c++ windows tr24731 c11

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

FILE *filepoint = (fopen(fileName, "r"));
Run Code Online (Sandbox Code Playgroud)

FILE *filepoint = (fopen_s(&,fileName, "r"));
Run Code Online (Sandbox Code Playgroud)

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

chq*_*lie 25

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

errno_t err = fopen_s(&filepoint, fileName, "r");
Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子:

#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.
}
Run Code Online (Sandbox Code Playgroud)

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

  • @Assimilater:“fopen”没有真正的“问题”。Visual Studio 可能会生成警告,提示用户使用“fopen_s()”编写可移植性较差的代码。“fopen_s”中添加的有关默认权限和独占模式的语义最好使用“fdopen”(如果可用)来解决。`strerror_s` 要求用户提供一个缓冲区,其长度应首先通过调用 `strerrorlen_s(err)` 计算。头痛根本不值得这么麻烦。 (3认同)
  • downvoter会关心解释吗? (3认同)
  • strerror与fopen有类似的问题。考虑修改以显示对我使用+1时使用strerror_s吗? (2认同)