C++ 文件路径问题

C++ File Paths Issue

当我使用此代码加载图像以供 SDL 渲染时:

SDL_Texture* testimg = IMG_LoadTexture(renderer, "testz.bmp");

(或)

SDL_Texture* testimg = IMG_LoadTexture(renderer, "/testz.bmp");

图像根本不呈现。但是...如果我使用此代码:

SDL_Texture* testimg = IMG_LoadTexture(renderer, "../bin/testz.bmp");

SDL 可以很好地绘制图像。 "bin" 是 .exe 所在的文件夹。那么如何解决此文件路径问题?

编辑:另一种可能性是 visual studio,出于某种原因,是 运行 它放在另一个位置的 bin 文件夹中没有图像的 exe...

因为你的可执行文件的安装目录与操作系统启动进程的当前目录不同,当它运行这个可执行文件时。

很明显,您启动的进程的当前目录是其可执行文件的兄弟目录。

可能有用的一件事是使用 argv[0] 来确保使用了正确的基本路径。假设您使用的是标准 main(),它会是这样的:

std::string base_path;
int main(int argc, char* argv[]) {
    base_path = argv[0];
    size_t last_slash = base_path.find_last_of('/');
    if(last_slash == std::string::npos)
        base_path = ".";
    else base_path.erase(last_slash + 1);
    // Anything else you need to do in `main()`
    return 0;
}

然后您的加载将如下所示:

SDL_Texture* testimg = IMG_LoadTexture(renderer, base_path + "testz.bmp");

如果它与 main() 在不同的文件中,您还需要使用 extern:

重新声明 base_path
extern std::string base_path;

当然,您需要 #include <string> 才能正常工作。

如果您的所有加载都在 main() 中完成,您可以通过将 base_path 的声明移至 main():

来改善这一点
int main(int argc, char* argv[]) {
    std::string base_path = argv[0];
    // The rest is the same
}