简体   繁体   English

freopen() 不读取/写入现有文件,niether 在 vscode 中创建新文件

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

I am trying to read input and output from two separate text files in C++.我正在尝试从 C++ 中的两个单独文本文件中读取输入和 output。

Code(test.cpp):代码(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:输入.txt:

1

output.txt is empty output.txt 为空

In VS code when using terminal and writing the commands:在 VS 代码中使用终端并编写命令时:

g++ test.cpp g++ test.cpp

.\a.exe .\a.exe

the data from input text file is read and data is written to the output text file.读取输入文本文件中的数据并将数据写入 output 文本文件。

Result after Running运行后的结果

But if I use Debugging, the input and output files does not get recognized by the program.但是如果我使用调试,输入和 output 文件不会被程序识别。 No input and output is read/written.无输入,output 被读/写。 No error is shown and the program just ends.没有显示错误,程序刚刚结束。

Result after using Debugging使用调试后的结果

launch.json:发射.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.我希望文本文件的输入/输出也能在调试时发生。

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.launch.json文件中, "cwd"值是正在启动或调试的进程的当前工作目录的路径,这是读取输入文件和output文件默认写入的位置。

You should set it to the directory where the files you are working with are located.您应该将其设置为您正在使用的文件所在的目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM