【问题标题】:E0167 error : C++ argument of type * is incompatible with parameter of type "FILE**"E0167 错误:* 类型的 C++ 参数与“FILE**”类型的参数不兼容
【发布时间】:2021-03-23 09:16:34
【问题描述】:

我对 C 非常陌生,在处理书中的示例时,我不断收到“C++ 类型 * 的参数与 ** 类型的参数不兼容”错误。我正在使用 Visual Studio 2019 C++。这是我使用 fopen_s 时出现错误的地方:

#include<stdio.h>
#include<stdlib.h>

int main()
{
FILE *inFile;

inFile = fopen_s("prices.dot","r"); /*Here is the line with an error*/

if (inFile == NULL)
{
    printf("\nThis file does not existL");
    printf("\nPlease make sure that this file currently exist");
    exit(1);

}

printf("\nThe file has been succfully open for reading.");

return(0);
}

当我使用“fopen”时,我收到一个警告,告诉我使用 fopen_s,而当我使用 fopen_s 时,我收到另一个错误。我想知道我是否可以在这个问题上得到任何帮助。谢谢!

【问题讨论】:

  • 您使用的是 C 还是 C++?这段代码看起来都像 C。
  • fopen_s 的签名与fopen 不同。
  • fopen_s 的参数与fopen 不同。见docs.microsoft.com/en-us/cpp/c-runtime-library/reference/…
  • 我建议你关闭告诉你使用_s 版本函数的警告。这些都是微软特有的,所以你的代码不再是可移植的。
  • auto res = fopen_s(&amp;inFile, "prices.dot","r").

标签: c++ c visual-c++


【解决方案1】:

如果你google“MSDN fopen_s”并阅读Microsoft Developer Network上的文档,你会发现函数原型与fopen()并不完全相同:

errno_t fopen_s(
   FILE** pFile,
   const char *filename,
   const char *mode
);

这意味着您在该区域的代码将变为:

FILE *inFile;
errno_t errcode;

errcode = fopen_s(&inFile, "prices.dot","r"); 

if (errcode != 0) { /* do error handling, perhaps quit */ }

或者,您可以继续编写旧式 C 代码,只需使用“fopen()”并在文件顶部关闭 MSVC 编译器,添加以下 #define:

#define _CRT_SECURE_NO_WARNINGS

请注意,fopen_s() 已添加到 C 2011 标准中,并在第 K.3.5.2.1 节中进行了描述——这意味着这仍然是任何现代 C 编译器上的可移植 C 代码。

您的书可能早于 2011 年,当时这个函数还不是 C 语言的一部分。

【讨论】:

  • 感谢大家的回答和建议。是的,我使用的是 C。我使用 #define _CRT_SECURE_NO_WARNINGS 关闭了警告。它奏效了。
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
相关资源
最近更新 更多