先来看一个简单的程序:

 

#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;
}

 

 

 

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

  


本文转载:CSDN博客