我要将图像放到我的sdl应用程序中,为此我需要知道它的路径。当我将完整路径放入IMG_Load()
函数时,它可以工作。当我尝试使用windows.h函数GetModuleFileName()
并将其与另一个字符数组合并时,我得到:
C:\ Users \ micro capacitor \ source \ repos \ 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);
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;
}
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