You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VSCode调试C++程序时传入文件参数提示无法打开文件怎么办?

问题描述

在Linux笔记本上配置VSCode进行C++开发,希望调试时实现终端执行./program.exe t2.txt的效果。修改launch.json后程序能识别参数,但执行以下代码时抛出“Cannot open file.”运行时错误:

std::ifstream file(filename);  // open file
if (not file) {
    throw std::runtime_error("Cannot open file.");
}

修改后的launch.json内容如下:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "C/C++: g++ build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": ["1","<","${workspaceFolder}/t2.txt"],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
                    "description": "Set Disassembly Flavor to Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++ build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}
问题原因与解决办法
  • 核心问题:launch.json的args配置错误。你在参数里加入了<,这是Shell的输入重定向符号,但VSCode调试时不会通过Shell解析命令,<会被当成普通的命令行参数传给程序,而非实现重定向逻辑。同时你的需求是直接将t2.txt作为程序的命令行参数(对应终端./program.exe t2.txt),而非通过重定向输入。
  • 修正方案:
    1. 调整args配置:如果你的程序需要的参数是1和t2.txt的路径,直接写成:
      "args": ["1", "${workspaceFolder}/t2.txt"]
      
      如果只需要t2.txt作为参数,则改为:
      "args": ["${workspaceFolder}/t2.txt"]
      
    2. 路径验证:确保t2.txt的路径正确。如果文件和当前调试的C++源文件在同一目录,也可以用${fileDirname}/t2.txt替代${workspaceFolder}/t2.txt。
    3. 确认程序逻辑:你的代码是通过命令行参数获取文件名,而非从标准输入读取,所以不需要使用重定向符号,直接传递文件路径参数即可。

内容的提问来源于stack exchange,提问作者Steve Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 19:12:08