Code does not create .txt files to output
Updated: this code is working on friend's PC, but on on my PC. We both installed same mingw file. Both have Windows 11, both tried on VS code and Far Manager
Hi. Here is following code:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
using namespace std;
int main() {
freopen("input.txt","r",stdin);
int a,b;
cin >> a >> b;
cout << a + b << endl;
freopen("output.txt","w",stdout);
cout << a + b << endl;
}
Code succesfully read integers a,b from file input.txt and outputs them in console, but freopen it do nothing. I tried ofstream fout("output.txt") also and it did not work. I tried this in Visual Studio Code with Code Runner and Far Manager with than line on compilation used on both:
g++ --std=c++17 !.! -DLOCAL -O2 -Wall -Wl,--stack=67108864 -o !.exe
For VS code I tried debug cwd (current working directory) and it was correct, I also checked .json files such as tasks.json and launch.json with it's cwd.
I have tried this code on Visual Studio (not VS code) and it worked! Maybe, the problem is in Windows 11? No antivirus programs on PC, no Windows Defender, no virtual machine, no windows 11 UAC.
Tried this code to get an error, but it seems like no errors occured.
FILE* file = freopen("output.txt", "w", stdout);
if (file == NULL) {
perror("Error opening file\n");
printf("errno: %d, description: %s\n", errno, strerror(errno));
}
else {
printf("File reopened successfully.\n");
}
std::ofstreamlearncpp.com : 28.6 — Basic file I/Ofreopenreturns. If it fails, usestrerrorto get a printable string of the error fromerrno. And to emphasize what others have said, use standard C++ facilities for all your file input and output.