Let's take a look at a simple program:
#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\ Desktop \cpp\test\debug\test.exe return
0;
}
However, if you use the above road strength in the program, it is not, because \ in C language is the escape character, we look at the following:
#include <fstream>
using namespace std;
int main ()
{
ofstream outfile ("C:\Documents and settings\administrator\ Desktop \mycpp\test.txt"); Test.txt files will not be generated
outfile << "Hello World" << Endl;
return 0;
}
And the following procedure is OK:
#include <fstream>
using namespace std;
int main ()
{
ofstream outfile ("C:\\Documents and settings\\administrator\\ Desktop \\MYCPP\test.txt"); Will generate Test.txt file
outfile << "Hello World" << Endl;
return 0;
}
We continue to look at:
#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\ desktop \cpp\test\debug\test.exe
if (0 = strcmp (szbuf, "c:\\ Documents and settings\\administrator\\ Desktop \\cpp\\test\\Debug\\test.exe ")"
{
cout << "yes" << Endl Yes
}
else
{
cout << "no" << Endl;
}
return 0;
}
Don't be surprised, \ is the escape symbol, \ \ Only represents a \, so the following code is wrong:
int main ()
{
char c = ' \ ';//Error return
0;
}
Based on the above discussion, let's get back to the point where the code for the current path is:
#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 = ' n ';
strcat (Szbuf, "\\test.txt"); To emphasize, strcat is very unsafe
cout << szbuf << Endl;//It is double slash, output shows a single slash of Ofstream outfile
(SZBUF);//Will generate TE St.txt file
outfile << "Hello World" << Endl;
return 0;
}
In short, understanding the escape symbol, everything is simple.