C:fopen_s()返回NULL如果它有效,所以我不能用flose()关闭它,它也不能与fwrite()一起工作

通常我会使用,fopen但对于 Visual Studio,您必须使用安全变体fopen_s. 但是因为如果操作成功则fopen_s返回一个NULL指针,所以我不能使用该fclose()函数来关闭与文件的连接。fclose(filePointer)是不可能的,因为它是一个 NULL 指针。如果我想使用类似fwrite()fread()那样的功能也不起作用。

我的问题是当我使用fwrite(str, 1, sizeof(str), filePointer)->“filePointer 可能为 0”。因为它是 0,因为如果 fopen_s(filePointer) 运行良好,我会得到“0”。

不幸的是,我在任何地方都找不到安全变体的任何示例,因为每个人都使用“正常”变体。我知道我可以关闭安全功能,但我真的不想这样做,因为安全实际上是件好事:D

回答

一个例子就在微软的 doco 页面上(这里有删节):

FILE *stream;
errno_t err = fopen_s(&stream, "crt_fopen_s.c", "r");
if (err == 0) {
    fclose(stream);
}

的第一个参数fopen_s是指向将接收文件句柄的变量的指针,因此您可以使用变量对文件执行任何操作(这只是在我上面的示例中关闭它)。


请注意,这些函数并不安全,尽管它们可能比原始函数更安全。他们检查特定NULL值,但有很多不安全的指针不是 NULL(a)

我一直认为良好的代码设计使这些检查变得不必要,尽管我意识到有些人可能不同意(b)。我放在 C 程序中的第一行可能是:

#define _CRT_SECURE_NO_WARNINGS

以免不得不忍受认为是微软的保姆状态。


(a)例如(void*)42,例如。

(b)他们当然是错的。

  • UV for the additional remarks. A big danger of the supposedly safer versions is that users can think they are otherwise compatible. One such example is `scanf_s()` which isn't a drop-in replacement for `scanf()` but takes additional arguments when certain format specifiers are used.
  • There are multiple reasons for MS's purportedly "secure" alternative functions not having been widely accepted outside MS's own ecosystem, but among them is that in practice, they are not much safer or more secure. You still need good code design and careful implementation to write safe code, and if you have those then indeed they are sufficient.

以上是C:fopen_s()返回NULL如果它有效,所以我不能用flose()关闭它,它也不能与fwrite()一起工作的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>