【问题标题】:How to go from fopen to fopen_s如何从 fopen 到 fopen_s
【发布时间】:2015-04-25 19:53:49
【问题描述】:

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

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

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

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

【问题讨论】:

  • fopen_sis documented at MSDN。第一个参数应该是FILE**,返回值是errno_t
  • 谷歌“MSDN fopen_s”
  • F1 在 Visual Studio 中不再工作了吗?
  • 我只会设置编译器设置来阻止警告消息。

标签: c++ c windows c11 tr24731


【解决方案1】:

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

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

这是一个完整的例子:

#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 对 C99 的支持笨拙且不完整。 Visual Studio 对有效代码产生警告,强制使用标准但可选的扩展,但在这种特殊情况下似乎不支持strerrorlen_s。更多信息请参考Missing C11 strerrorlen_s function under MSVC 2017

【讨论】:

  • strerror 与 fopen 有类似的问题。考虑修改以显示我对 strerror_s 的 +1 的使用?
  • @Assimilater:fopen 没有真正的问题。 Visual Studio 可能会产生警告,提示用户使用fopen_s() 编写可移植性较差的代码。 fopen_s 中添加的关于默认权限和独占模式的语义最好在可用时使用fdopen 解决。 strerror_s 要求用户提供一个缓冲区,其长度应首先通过调用 strerrorlen_s(err) 计算。头痛不值得麻烦。
  • @Assimilater:不过,我编辑了答案并为这两种方法提供了代码。
  • 我的意思是,当我使用 strerror(err) 时,我从 Visual Studio 收到了与使用 fopen 相同的警告(阻止我编译)。 ://
  • @nurp:微软对 C99 的支持笨拙且不完整。 VS 对有效代码产生警告,强制使用可选的标准扩展,但在这种特殊情况下似乎不支持strerrorlen_s。更多信息请参考stackoverflow.com/questions/44430141/…
猜你喜欢
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多