34

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

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

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

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

4

1 回答 1

46

fopen_s是一个“安全”的变体,fopen带有一些用于模式字符串的额外选项以及用于返回流指针和错误代码的不同方法。它由 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. 有关详细信息,请参阅MSVC 2017 下的 Missing C11 strerrorlen_s 函数

于 2015-02-24T13:12:01.263 回答