【问题标题】:freopen() does not read / write to existing file, niether creates new file in vscodefreopen() 不读取/写入现有文件,niether 在 vscode 中创建新文件
【发布时间】:2021-02-04 15:54:11
【问题描述】:

我正在尝试从 C++ 中的两个单独文本文件中读取输入和输出。

代码(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;
}

输入.txt:

1

output.txt 为空

在 VS 代码中使用终端并编写命令时:

g++ test.cpp

.\a.exe

读取输入文本文件中的数据并将数据写入输出文本文件。

Result after Running

但是如果我使用调试,输入和输出文件不会被程序识别。没有输入和输出被读/写。没有显示错误,程序就结束了。

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"
    }
]

}

我希望文本文件的输入/输出也能在调试时发生。

【问题讨论】:

  • 当前工作目录“cwd”应该是包含您的文件的目录。

标签: c++ visual-studio-code freopen


【解决方案1】:

好的,我知道这里发生了什么。在launch.json 文件中,"cwd" 值是正在启动或调试的进程的当前工作目录 的路径,这是读取输入文件和输出文件并写入的位置默认情况下。

您应该将其设置为您正在使用的文件所在的目录。

【讨论】:

  • 我自己在头疼之后才弄明白的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 2013-03-31
  • 2011-06-22
  • 2013-01-14
相关资源
最近更新 更多