【问题标题】:C++: Why can't I open a file with a relative path?C++:为什么我不能用相对路径打开文件?
【发布时间】:2021-01-22 03:11:32
【问题描述】:

以前用Visual Studio 2019开发C和C++程序,现在转到VS Code,调试的时候发现不能用相对路径打开文件,只能用绝对路径才能工作.

这是我的 launch.json 和 tasks.json 文件:

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": "gcc.exe - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "C:\\mingw64\\bin",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\mingw64\\bin\\gdb.exe",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: gcc.exe build active file"
        }
    ]
}

tasks.json:

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: gcc.exe build active file",
            "command": "C:\\mingw64\\bin\\gcc.exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:\\mingw64\\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

非常感谢您解决了我的问题。

【问题讨论】:

  • 在启动时检查程序的“当前工作目录”,通过GetCurrentDirectory() 或等效。路径可能不是您所期望的。这就是为什么你不应该使用相对路径开始的原因。
  • 究竟您正在执行的“打开具有相对路径的文件”失败的过程是什么?
  • 相对路径(很好)相对于程序的当前工作目录。如果您的程序的当前工作目录设置不正确(例如,设置为包含各种预期子目录的目录),则相对路径不起作用。同样正确的是,如果您尝试使用不存在的绝对路径打开文件,则绝对路径不起作用。

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


【解决方案1】:

从应用程序的当前工作目录遇到相对路径,并且您已提供

"cwd": "C:\\mingw64\\bin",

如果您想从当前项目根目录运行,请将其设置为这样(或将其设置为您喜欢的位置)

"cwd": "${workspaceRoot}"

编辑:如果您以这种方式设置它以便能够运行 gcc,请考虑在您的 PATH 变量中添加 C:\\mingw64\\bin

【讨论】:

    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2017-09-05
    相关资源
    最近更新 更多