簡體   English   中英

std::ifstream 構造函數只接受絕對路徑?

[英]std::ifstream constructor only accepts absolute path?

我正在嘗試使用ifstream構造函數打開文件,但找不到使用相對路徑的方法。
所有文件都在同一個文件夾中,名為: example

在 Linux 上,我使用: ifstream file("/home/username/New Volume/VSCode Projects/example/p1.txt");

在 Windows 上,我使它與: ifstream fisier("D:\\Projects\\VSCode Projects\\example\\p1.txt");

我嘗試了一些組合,但沒有任何效果:

// Linux
ifstream file("p1.txt");
ifstream file("./p1.txt");
ifstream file("../p1.txt");

// Windows
ifstream file("p1.txt");
ifstream file("\p1.txt");
ifstream file("\\p1.txt");
ifstream file(".\p1.txt");
ifstream file(".\\p1.txt");

.vscode文件夾內有:

// 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": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "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"
        }
    ]
}

// settings.json
{
    "files.associations": {
        "iosfwd": "cpp"
    }
}

// tasks.json
{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++.exe build active file",
            "command": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

ifstream的正確相對路徑是什么?

ifstream file("p1.txt");

這行得通。 根據在您的完整文件路徑中看到“VSCode 項目”,我猜問題是您沒有在 Visual Studio Code 中正確配置當前工作目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM