65.9K
CodeProject is changing. Read more.
Home

Converting TCHAR[] to string, while getting PC Name

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (3 votes)

May 17, 2010

CPOL

2 min read

viewsIcon

18690

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...

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. strPCName.assign(pMBBuffer); // Here you need to include windows.h,string.h and iostream.h using namespace std; string GetSystemName() { string strPCName;// String to hold system name. size_t size = MAX_COMPUTERNAME_LENGTH + 1; // maximum system name length + 1 DWORD dwBufferSize = size; // size of storage buffer. TCHAR tchrSystemName[MAX_COMPUTERNAME_LENGTH + 1]; // Allocate the TCHAR memory. // Get the system name. if(GetComputerName(tchrSystemName,&dwBufferSize)) { char *pMBBuffer = (char *)malloc( size ); wcstombs_s(&size, pMBBuffer, (size_t)size,tchrSystemName, (size_t)size);// Convert to char* from TCHAR[] strPCName.assign(pMBBuffer); // Now assign the char* to the string, and there you have it!!! :) free(pMBBuffer); } else // Failed to find the system name. strPCName.clear(); return strPCName; } void main(void) { cout<<GetSystemName().c_str(); }