如何在 Visual C++ 中打开文件?

How can i open a file in visual c++?

我正在使用 visual studio,但在打开此文本文件时遇到问题 我已将其与所有源代码放在文件夹中,但我收到 "No such file or directory" 错误。这是我的代码

void Game::load_map(const char *filename)
{
    int width,height,current;
    std::ifstream in(filename);
    if(in.fail()){
        std::cout << "problem opening the file" <<std::endl;
        perror(filename);
    }
    else
    {
        in >> width;
        in >> height;
        for(int i = 0; i < height; i++)
        {
            std::vector<int> vec;
            for(int j = 0; j<width;j++)
            {
                if(in.eof())
                {
                    std::cout<< "file ends error" << std::endl;;
                    return;
                }
                in >> current;
                if(current>=0 && current<=1)
                {
                    vec.push_back(current);
                }else{
                    vec.push_back(0);
                }
            }
            map.push_back(vec);
        }
    }
    in.close();
}

这就是我调用此函数的方式:

load_map("map.map");

您的程序可能 运行 不在放置源代码的同一目录中,而是在 Solution\Debug 目录中。

将相对于此目录的文件路径传递给您的函数

load_map("..\Project\map.map");

或将您要打开的文件移至此处。或者第三个选项,如果您不确定程序的工作目录在哪里,请提供完整路径

load_map("c:\Blah\Blub\Project\map.map");