【问题标题】:why is freopen() not working on Microsoft Visual Studio but working on CodeBlocks?为什么 freopen() 不能在 Microsoft Visual Studio 上工作,而是在 CodeBlocks 上工作?
【发布时间】:2020-03-11 22:03:47
【问题描述】:

我开始 C++ 的时间不长,并且非常努力地寻找不同的方法来读取和写入文件,但没有结果,直到我在 CodeBlocks 上尝试了它,它有效。虽然下面附有图像以指出代码中可能存在的错误两个应用程序使用了相同的代码。

错误代码: Severity Code Description Project File Line Suppression State Suppression State Error C4996 'freopen': This function or variable may be unsafe. Consider using freopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. Codeforces C:\Users\owamoyo\source\repos\Codeforces\Codeforces.cpp 6

#include<bits/stdc++.h>

using namespace std;

int main() {
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    int n; cin >> n;
    while (n--) {
        int x; cin >> x;
        cout << x << " ";
    }
    return 0;
}

#include<bits/stdc++.h>

using namespace std;

int main() {
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    int n; cin >> n;
    while (n--) {
        int x; cin >> x;
        cout << x << " ";
    }
    return 0;
}

【问题讨论】:

  • 你有什么理由让自己首先经历这种痛苦吗?您正在做的事情使插入调试输出和其他有用的诊断变得烦人。您可以像普通的常规文件流一样打开 input.txt 和 output.txt 并对这些流进行操作。
  • 不相关:出于多种原因使用代码is usually a bad idea 的图像。 So is #include &lt;bits/stdc++.h&gt;.
  • 不过,出于兴趣,您需要做什么才能让 Visual Studio 接受#include &lt;bits/stdc++.h&gt;?自己滚?从 GCC 中提取文件?
  • MSVC 对有效代码发出警告,试图诱使您使用他们的专有东西
  • 此处的所有问题都必须包含所有相关信息在问题本身中以纯文本形式。链接可以随时停止工作,使问题变得毫无意义。无法复制/粘贴以图像形式显示的代码、数据或错误;或编辑或编译以供进一步研究和调查。这个问题必须是edited,并且所有链接和图像都被删除并替换为所有相关信息,作为纯文本。所有代码必须满足minimal reproducible example 的所有要求。您可以在这里找到许多其他问题,其中包括纯文本形式的所有内容,我看不出为什么这个问题也不能。

标签: c++ visual-c++ codeblocks freopen


【解决方案1】:
  • 首先将此添加到您的代码中
#define _CRT_SECURE_NO_DEPRECATE
#include<stdio.h>
#include<stdlib.h>
  • 然后将input.inoutput.out 添加到您的项目中
  • 然后右键单击解决方案资源管理器并选择
    • 属性
      • 配置
        • C/C++
          • 预处理器 然后编辑 Preprocessor Definitions 并将其更改为_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)

Steps

【讨论】:

    【解决方案2】:

    只需使用freopen_s 或者 转到 Project->Properties->Configuration Properties->C/C++->Preprocessor->Preprocessor Definitions 并添加 _CRT_SECURE_NO_WARNINGS

    例子:

    FILE *input;
    
    errno_t e = freopen_s(&input, "input.txt", "w", stdin);
    if(e)
        /* Handle that error(cannot reopen) */;
    
    ...
    
    fclose(input);
    

    【讨论】:

    • 注意:此函数或变量可能不安全警告是 Visual Studio 的编译器警告您,如果正确使用该函数可能会失败并建议您使用 (以前是 Microsoft 特定的)替代方案,用于清除一些故障点。基于 GCC 的编译器假定您知道自己在做什么并正确使用该函数,并且不会警告您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2017-06-26
    相关资源
    最近更新 更多