首页 > 解决方案 > 无法从文件中读取

问题描述

在遵循vulkan-tutorial时,我遇到了一个问题。我根本无法使用他使用的方法打开文件。

我有一个名为 shader.frag.spv 的文件,它是编译成 spir-v 代码的片段着色器。它在我的源文件夹中,我readFile也在其中。

这是重现我的问题的代码:

#include <iostream>
#include <fstream>

void readFile(const std::string& filename) {
    std::ifstream file(filename, std::ios::ate | std::ios::binary);

    if (file.is_open())
        std::cout << "test";
    else
    {
        std::cin.get(); // I always land on the else block
    }
}

int main()
{
    readFile("shader.frag.spv");
}

重新启动 Visual Studio,更改文件名,更改其内容,将其移动到单独的文件夹,使用绝对路径。这些都没有解决我的问题。

有任何想法吗?

标签: c++filefstream

解决方案


鉴于该文件已经在您当前的工作目录中,该代码应该可以工作,请检查!

默认情况下,Visual Studio 中的当前目录是项目根目录,而不是可执行文件所在的位置,正如@someProgrammerDude 提到的那样。

如果您不确定,请检查C++ Visual Studio Current Working Directory


推荐阅读