why is freopen() not working on Microsoft Visual Studio but working on CodeBlocks?

5.5k Views Asked by At

I started C++ not so long and searched so hard for different ways to read and write from/to files with no result until i tried it out on CodeBlocks which worked.. Images are attached below to point out possible errors in code though the same code were used on both applications.

Error Code: 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

Code Blocks

#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;
}

MS Visual Studio

#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;
}
3

There are 3 best solutions below

0
MahmouD Skafi On BEST ANSWER
  • First of all add this to your code
#define _CRT_SECURE_NO_DEPRECATE
#include<stdio.h>
#include<stdlib.h>
  • then add input.in and output.out to your project
  • then right click in solution explorer and select
    • Properties
      • Configurations
        • C/C++
          • Preprocessor then edit Preprocessor Definitions and change it to_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)

Steps

1
mylibh On

Just use freopen_s or go to Project->Properties->Configuration Properties->C/C++->Preprocessor->Preprocessor Definitions and add _CRT_SECURE_NO_WARNINGS

Example:

FILE *input;

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

...

fclose(input);
1
Chuning Liu On
#include<bits/stdc++.h>

is not supported in visual studio. the reason that it is supported in most other coding IDEs is because of the bits/stdc++ folder, which contains all the usual headers you will need, like algorithm and iostream. Visual studio apparently does not have such a folder, or does not allow this folder to be included by the #include<...>