freopen() does not read / write to existing file, niether creates new file in vscode

924 Views Asked by At

I am trying to read input and output from two separate text files in C++.

Code(test.cpp):

#include<bits/stdc++.h>
using namespace std;
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    #endif

    int x = 6 ;
    cin >> x;
    cout << x;
}

input.txt:

1

output.txt is empty

In VS code when using terminal and writing the commands :

g++ test.cpp

.\a.exe

the data from input text file is read and data is written to the output text file.

Result after Running

But if I use Debugging, the input and output files does not get recognized by the program. No input and output is read/written. No error is shown and the program just ends.

Result after using Debugging

launch.json:

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
    {
        "name": "g++.exe - Build and debug active file",
        "type": "cppdbg",
        "request": "launch",
        "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
        "args": [],
        "stopAtEntry": false,
        "cwd": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin",
        "environment": [],
        "console": "externalTerminal",
        "MIMode": "gdb",
        "miDebuggerPath": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\gdb.exe",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ],
        "preLaunchTask": "C/C++: g++.exe build active file"
    }
]

}

I want the input/output from text file to happen while debugging as well.

1

There are 1 best solutions below

1
On BEST ANSWER

Okay, I get what is happening here. In the launch.json file, the "cwd" value is the path of the current working directory of the process being launched or debugged, this is where the input files are read from and output files and written to by default.

You should set it to the directory where the files you are working with are located.