Hi there,
Its been a while since I wrote my last article. Since got myself into a problem of getting the system name of my PC.
I dragged my C instincts into the MSDN world of asking how to get the PC name.
After fiddling for a while I got hold of the PC name, not that difficult as a single line function needed to be called.
But the problem is where I had to convert TCHAR[] to a string. Wow, really never thought I would ever go round and round in circles.
So much for the background. This small code snippet actually helps converting TCHAR array to a simple string. With a delecate approach not to make use or leave a corrupted memory, I wrote down the code with some help from MSDN.
I am amazed that such a simple task usually not that easily available ofter lots of Googling and Yahooing.
Anyaway, here is the code that takes care of converting TCHAR to a simple string.
The code begins with a function that gets the PC name. This encloses the code where the I had to convert a TCHAR[] to a
string.
First, the correct lengths and storage sizes for TCHAR[] and a char* buffer had to be established. After correctly establishing
the correct lengths, all that was left to use the wcstombs_s() function that actually does the conversion. This is essentially
a data copying function which takes care of converting the TCHAR[] to a char*.
wcstombs_s(&size, pMBBuffer, (size_t)size,tchrSystemName, (size_t)size);
After so, a simple assignment of the storage string was performed with the following
line of code.
<br />
strPCName.assign(pMBBuffer); <br />
<br />
<br />
using namespace std;<br />
<br />
string GetSystemName()<br />
{ <br />
string strPCName;
size_t size = MAX_COMPUTERNAME_LENGTH + 1;
DWORD dwBufferSize = size;
TCHAR tchrSystemName[MAX_COMPUTERNAME_LENGTH + 1];
<br />
if(GetComputerName(tchrSystemName,&dwBufferSize)) <br />
{ <br />
char *pMBBuffer = (char *)malloc( size );<br />
wcstombs_s(&size, pMBBuffer, (size_t)size,tchrSystemName, (size_t)size);
strPCName.assign(pMBBuffer);
free(pMBBuffer);<br />
} <br />
else
strPCName.clear(); <br />
return strPCName; <br />
}<br />
<br />
<br />
void main(void)<br />
{<br />
cout<<GetSystemName().c_str();<br />
} <br />