在使用 vs 代码调试文件时,如何将文件传递到我的程序中

How can I pass a file into my program, when debugging it with vs code

本文关键字:文件 程序 我的 vs 代码 调试      更新时间:2023-10-16

我想启动一个.exe(一个编译的cpp程序),并将一个文件传递给它。在 CMD 上,我会像a.exe < input.txt一样做.如何在调试模式下使用 VS Code 启动它?

这是我的启动.json文件:

{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/a.exe",
"args": [
"<",
"input.txt"
],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": true,
"miDebuggerPath": "C:\MinGW\bin\gdb.exe",
"linux": {
"MIMode": "gdb"
},
"osx": {
"MIMode": "lldb"
},
"windows": {
"MIMode": "gdb"
}
}
]}

args我已经尝试使用"<", "input.txt",就像这篇文章中建议的那样,"<input.txt"这篇文章中的建议。两者都不起作用。如此处建议的那样,在 cmd 上进行调试似乎是一种非常糟糕的做法。当我拥有 vs 代码的出色调试工具时,为什么要在 cmd 上进行调试?

我在Windows机器上运行。

您缺少的是告诉 gdb 文件的实际位置。尝试提供输入文件时,您需要将文件的位置放在引号中,因此它看起来像这样:

{
"version": "0.2.0",
"configurations": [
{
"name": "g++ - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [
"<", "${fileDirname}/words5.txt"
],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true

}
],
"preLaunchTask": "C/C++: g++ build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}

另一种选择是在 a.cpp 文件中添加这些行。

freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);

所有 cin 和 cout 都将使用输入.txt和输出.txt。