How to convert TCHAR to const char?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#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);
		

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" on VS 2013.
Last edited on
The question is meaningless. A const char is constant. You can't write to a constant value.

Is it possible you're encountering this situation?
1
2
3
4
5
void function_you_need_to_call(const char *);

TCHAR c_wPath[MAX_LEN] = _T("Hello world!");
//???
function_you_need_to_call(converted);
If this is the case, the code you have will work. A 'T *' is freely convertible to a 'const T *'.
1
2
3
4
TCHAR c_wPath[MAX_LEN] = _T("Hello world!");
char converted[MAX_LEN];
wcstombs(converted, c_wPath, wcslen(c_wPath) + 1);
function_you_need_to_call(converted);

A couple notes:
1. A Unicode string of MAX_LEN characters may need more than MAX_LEN chars after being converted by wcstombs(). Your c_szPath could end up incomplete.
2. The last parameter you passed to wcstombs() is wrong. You're supposed to pass the size of the destination array, not the length of the source string. You should pass MAX_LEN, because that's the size you gave to c_szPath (not c_wPath).
3. The behavior of wcstombs() and related functions depends on system locale settings. Be aware that if you send this code to other people it may behave differently on their computers!
thx, already solved
Topic archived. No new replies allowed.