Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Combine 2 Tchar

Tags:

c++

tchar

I'm trying to combine 2 tchar.

char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
TCHAR* appdatapath ="C:\\Users\\"+username+"\\AppData";

But I get error error at appdatapath line. How can I combine 2 tchar? Thanks

like image 930
backspace Avatar asked Feb 05 '14 13:02

backspace


2 Answers

Have a look at strcat and wcscat. You can't add char pointer with char array.

If you are on a windows machine, you can use _tcscat which will redirect to the right function to use depending on _UNICODE and _MBCS defines.

Might want to use the safe versions as well by appending _s to the function name.


As pointed in the comments, you can also use snprintf like so:

const size_t concatenated_size = 256;
char concatenated[concatenated_size];

snprintf(concatenated, concatenated_size, "C:\\Users\\%s\\AppData", username);

Since you have string literals before and after the runtime string, it is probably a better approach.

like image 97
Eric Fortin Avatar answered Sep 25 '22 11:09

Eric Fortin


To answer the question in the title: you concatenate two TCHAR strings using the _tcscat function.

However, there are other issues in your code related to this: GetUserName expects a LPTSTR, i.e. a pointer to a buffer TCHAR characters. Furthermore, there's another TCHAR usage in

TCHAR* appdatapath ="C:\\Users\\"+username+"\\AppData";

The issue with this is that the type to which TCHAR expands changes depending on whether _UNICODE is defined. In particular, if you set it, TCHAR (eventually) expands to wchar and hence GetUserName expects a wchar_t* but you pass a char*. Another issue is that you cannot concatenate C arrays using the + operator.

I suggest to stop worrying about TCHAR in the first place and always just compile with _UNICODE defined - and use wchar throughout your code. Also, since you're using C++, just use std::wstring:

wchar username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserNameW(username, &username_len);
std::wstring appdatapath = L"C:\\Users\\";
appdatapath += username;
appdatapath += L"\\AppData";

Last but not least: your entire code can probably be replaced with a call to the SHGetSpecialFolderPath function - pass CSIDL_APPDATA to it to get the "AppData" path.

like image 30
Frerich Raabe Avatar answered Sep 23 '22 11:09

Frerich Raabe