c++文件路径问题

C++ File Paths Issue

本文关键字:问题 路径 文件 c++      更新时间:2023-10-16

当我使用以下代码加载图像供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
}