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所在的文件夹。那么我如何修复这个文件路径问题呢?
因为您的可执行文件所在的目录与您的操作系统运行此可执行文件时启动的进程的当前目录不同。
很明显,已启动进程的当前目录是其可执行文件的兄弟目录。
可以使用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
}
相关文章:
- CMake 错误"源似乎不包含 CMakeLists.txt",路径/库连接问题
- 有效地将大数存储为 2 的幂用于路径问题
- 使用 Libssh 将文件从服务器复制到客户端:分配文件复制目标路径时出现问题
- 我最近更改了编译器路径以运行 c++ 代码,但现在我无法运行任何 python 代码。我该如何解决这个问题?
- 按名称问题获取卸载应用程序路径
- 从另一个应用启动我的应用时出现相对路径更改问题
- 问题在具有依赖性时从其他路径上加载DLL的DLL
- 程序文件中的安装路径:一些问题
- 在 c++ 中找不到头文件,可能的路径问题
- Visual Studio:C++\CLI 包装程序集路径依赖性问题
- 班级路径问题 - getJnienv失败了
- 最短路径问题与一个变化
- 我的递归算法中的问题,用于查找所有最短、唯一的路径
- 编译C++中动态链接库,存在运行路径问题
- 问题:如何在任何Windows机器上使用路径创建文件
- qt5设计器,使用fileopen,在lineedit中显示文件路径,这样做是否有问题
- IOS上的OpenCV haar级联了C++中的xml文件路径问题
- A* 路径查找中 std::map 性能的视觉C++性能问题
- 实现用于查找路径的递归函数时出现问题
- C++创建进程 - 系统错误#2找不到文件 - 我的文件路径有什么问题?