我要在我的sdl应用程序中放置一个图像,为此,我需要知道它的路径。当我将完整路径放入IMG_Load()
函数中时,它将起作用。当我尝试使用windows.h函数GetModuleFileName()
并将其与另一个字符数组结合在一起时,我得到:
C:\ Users \ micro 电容器\源\存储库\ FlatApoc \ x64 \ Debug \ FlatApoc.exe / Images / Play1.png
我要解决的问题是摆脱
FlatApoc.exe
从char数组。我已经知道
FlatApoc.exe
来自GetModuleFileName()
。解决此问题的方法只是从char数组中删除FlatApoc.exe,但是我对C ++还是很陌生,我不知道该怎么做。
我的代码是:
char path[MAX_PATH]; // The path of the executable
GetModuleFileName(NULL, path, sizeof(path)); // Get the path
char pathbuff[256]; // Buffer for the png file
strncpy_s(pathbuff, path, sizeof(pathbuff));
strncat_s(pathbuff, "/Images/Play1.png", sizeof(pathbuff));
Button_Play1 = IMG_Load(pathbuff);
答案 0 :(得分:1)
C ++方式。注意它看起来更自然:
#include <windows.h>
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
char path [MAX_PATH];
GetModuleFileName (NULL, path, sizeof (path));
std::string s = path;
auto n = s.rfind ('\\');
s.erase (n);
s += "/Images/Play1.png";
std::cout << s;
}
答案 1 :(得分:0)
Nvm。我现在修复了它,但是我将代码留在这里:
char path[MAX_PATH]; // The path of the executable
GetModuleFileName(NULL, path, sizeof(path)); // Get the path
char search[] = "\\FlatApoc.exe"; // The programs name
char *ptr = strstr(path, search);
*ptr = NULL;
char pathbuff[256]; // Buffer for the png file
strncpy_s(pathbuff, path, sizeof(pathbuff));
strncat_s(pathbuff, "/Images/Play1.png", sizeof(pathbuff)); // "/Images/Play1.png" was the link from the executables folder
Button_Play1 = IMG_Load(pathbuff); // Load image