c++visual-c++tchar

How concatenate a TCHAR array with a string?


i have the following code:

enter code here
TCHAR szSystemDirectory[MAX_PATH] ;
GetSystemDirectory(szSystemDirectory, MAX_PATH) ;
_stprintf(szSystemDirectory, _T("%s"), L"\\");

AfxMessageBox(szSystemDirectory);

and wants concatenate two slashes to szSystemDirectory variable, but final result always like this:

\

How solve?

thank you by any help or suggestion.


Solution

  • Not sure if the "two slashes" thing is not just something you see in the debugger (since it would show a single slash as an escaped one) but - the biggest issue you have is that your are overwriting the contents of szSystemDirectory with the _stprintf call. I guess what you wanted was to print the \ character at the end of the path. Try

    TCHAR szSystemDirectory[MAX_PATH + 2]; // 1 for null terminator, 1 for the slash
    UINT nCharactersWritten = GetSystemDirectory(szSystemDirectory, MAX_PATH);
    szSystemDirectory[nCharactersWritten] = _T('\\');
    szSystemDirectory[nCharactersWritten + 1] = _T('\0');
    

    or for two slashes:

    TCHAR szSystemDirectory[MAX_PATH + 3]; // 1 for null terminator, 2 for the slashes
    UINT nCharactersWritten = GetSystemDirectory(szSystemDirectory, MAX_PATH);
    szSystemDirectory[nCharactersWritten] = _T('\\');
    szSystemDirectory[nCharactersWritten + 1] = _T('\\');
    szSystemDirectory[nCharactersWritten + 2] = _T('\0');
    

    _stprint_f has been declared deprecated in Visual Studio 2015, so if you want to use the printing functions you can try:

    TCHAR szSystemDirectory[MAX_PATH + 2]; // 1 for null terminator, 1 for the slash
    UINT nCharactersWritten = GetSystemDirectory(szSystemDirectory, MAX_PATH);
    _stprintf_s(szSystemDirectory + nCharactersWritten, MAX_PATH + 2 - nCharactersWritten, _T("%s"), _T("\\")); 
    

    or for two slashes

    TCHAR szSystemDirectory[MAX_PATH + 3]; // 1 for null terminator, 2 for the slashes
    UINT nCharactersWritten = GetSystemDirectory(szSystemDirectory, MAX_PATH);
    _stprintf_s(szSystemDirectory + nCharactersWritten, MAX_PATH + 3 - nCharactersWritten, _T("%s"), _T("\\\\"));