如何获取当前运行的.exe所在路径的双斜线形式?---利用GetModuleFileName

972 篇文章 329 订阅
32 篇文章 6 订阅

        先来看一个简单的程序:

 

#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
	char  szBuf[1025] = {0};   
	GetModuleFileName(NULL, szBuf, sizeof(szBuf));
	cout << szBuf << endl; // C:\Documents and Settings\Administrator\桌面\cpp\test\Debug\test.exe

	return 0;
}


        但是, 你要是在程序中利用上述路劲, 就不行了, 因为\在C语言中是转义字符, 下面我们看看 :

 

 

#include <fstream>
using namespace std;

int main()
{
	ofstream outFile("C:\Documents and Settings\Administrator\桌面\MYCPP\test.txt"); // 不会生成test.txt文件
	outFile << "hello world" << endl;

	return 0;
}


      而下面程序是ok的:

 

 

#include <fstream>
using namespace std;

int main()
{
	ofstream outFile("C:\\Documents and Settings\\Administrator\\桌面\\MYCPP\test.txt"); // 会生成test.txt文件
	outFile << "hello world" << endl;

	return 0;
}

 

       我们继续来看:

 

#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
	char  szBuf[1025] = {0};   
	GetModuleFileName(NULL, szBuf, sizeof(szBuf));
	cout << szBuf << endl; //   C:\Documents and Settings\Administrator\桌面\cpp\test\Debug\test.exe

	if(0 == strcmp(szBuf, "C:\\Documents and Settings\\Administrator\\桌面\\cpp\\test\\Debug\\test.exe"))
	{
		cout << "yes" << endl; //   yes
	}
	else
	{
		cout << "no" << endl;
	}

	return 0;
}

 

 

 

      不要奇怪, \是转义符号, \\才表示一个\, 所以, 下面代码是错误的:

 

int main()
{
	char c = '\'; // error
	return 0;
}


     根据上面的讨论, 我们回到正题, 获取当前路径的代码为:

 

 

#include <windows.h>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	char   szBuf[1025] = {0};   
	GetModuleFileName(NULL, szBuf, sizeof(szBuf));
	
	char *p = strrchr(szBuf, '\\'); 
	*p = '\0'; 

	strcat(szBuf, "\\test.txt");  // 强调一下, strcat非常不安全

	cout << szBuf << endl; // 本身是双斜线的, 输出显示的是单斜线的

	ofstream outFile(szBuf); // 会生成test.txt文件
    outFile << "hello world" << endl;

	return 0;
}

 

 

 

        总之, 理解了转义符号, 一切都简单。

  

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值