Pranciskus
Pranciskus

Reputation: 539

How to convert TCHAR to const char?

The most similar thing I found is conversion to char. I'm trying to convert TCHAR "path" to const char. Btw I use character set: "Not Set".

#include <stdlib.h>
// ... your defines
#define MAX_LEN 100

TCHAR *systemDrive = getenv("systemDrive");
TCHAR path[_MAX_PATH];
_tcscpy(path, systemDrive);

TCHAR c_wPath[MAX_LEN] = _T("Hello world!");//this is original
//TCHAR c_wPath[MAX_LEN] = path; "path" shows error
char c_szPath[MAX_LEN];

wcstombs(c_szPath, c_wPath, wcslen(c_wPath) + 1);

Upvotes: 1

Views: 6940

Answers (1)

Boki
Boki

Reputation: 657

TCHAR is alias for different types depending of platform, defined macros, etc. so, TCHAR can be alias for char(1 byte) or WCHAR(2 bytes). further, WCHAR can be alias for wchar_t or unsigned short. But, you made conversion using wcstombs which has signature like size_t wcstombs(char *, const wchar_t *, size_t), so you have

char* c_szPath 

pointing to converted array of char, now, if you need const char*, it is probably enough to write simply const char * myPath = c_szPath, it is legal, and use myPath. But maybe, you even don't need this, because char* can bind on argument of type const char * if you need to pass it to function as argument. When you say,

"path" shows error

that is because array type is not assignable. I really hope this helps.

Upvotes: 1

Related Questions