Win32获取相对路径的方法

两个函数一个全局变量就可以搞定

static char LOGO_PATH[100]="";//先初始化一个地址
//拼接函数
void link(char *s, char *t)
{
	while (*s != '\0')
	{
		s++;
	}
	while (*t != '\0')
	{
		*s++ = *t++;
	}
	*s = '\0';
}
void Func_Pic_Path(char *ss)
{
	//路径
	TCHAR szFilePath[MAX_PATH + 1] = { 0 };
	char pic_path[100] = "pic\\";
	link(pic_path,ss);
	GetModuleFileName(NULL, szFilePath, MAX_PATH);
	(_tcsrchr(szFilePath, _T('\\')))[1] = 0; // 删除文件名,只获得路径字串
	char *str_url = szFilePath;  //例如str_url==e:\program\Debug
	wsprintf((char *)LOGO_PATH, str_url);
	link(LOGO_PATH, pic_path);//最终地址拼接
}

利用以上两个函数,可以用Func_Pic_Path(char *ss)这个函数输入从pic\之后的路径得到此时文件的相对路径
例如:

//这是文件相对exe在根目录下的路径
static char Main_Background[30] = "main\\Main_Background.png";
Func_Pic_Path(Main_Background);
//输出图片的现在路径
MessageBox(NULL,LOGO_PATH,"",NULL);

最后的路径显示"C:\…\pic\main\Main_Background.png"
(因为‘\’是转义字符,所以这里在写入都是默认的双斜杠,编译器用一个来转义,所以最后输出是单斜杠)

猜你喜欢

转载自blog.csdn.net/hu421160052/article/details/86711353