-1

I want to add an string to a LPTSTR.

The code is:

hSourceFile = CreateFile(
    pszSourceFile,
    FILE_READ_DATA,
    FILE_SHARE_READ,
    NULL,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    NULL);
if (INVALID_HANDLE_VALUE != hSourceFile)
{
    _tprintf(
        TEXT("The source plaintext file, %s, is open. \n"),
        pszSourceFile);
}

The pszSourceFile is a type of LPTSTR, but i want to add some extra text.

Like (not working)

pszSourceFile + ".txt"

What is the best way to do this?

ckruczek
  • 2,361
  • 2
  • 20
  • 23
De Fix
  • 1
  • 1
  • 4
    Please take a look for [this](http://stackoverflow.com/questions/308695/how-to-concatenate-const-literal-strings-in-c) question. Btw, WinAPI is C and not C++. – ckruczek May 17 '16 at 13:13
  • 1
    Why do you feel the need to support Windows 98? Wouldn't it be better to move into the 21st century and just use Unicode. Don't be tricked into thinking that `TCHAR` is still useful. – David Heffernan May 17 '16 at 14:50

2 Answers2

1

Considering the C-style and the use of the Windows API (with TEXT() et. al.); use _tcscat() or _tcsncat() (the later requires a buffer size).

For example;

TCHAR buffer[1024] = {}; // or '\0'
_tcsncat(buffer, pszSourceFile, 1024);
_tcsncat(buffer, TEXT(".txt"), 1024);

Demo.

Warning; watch out for your buffer overruns. Assuming the "normal" Windows 260 character path file and name limits (_MAX_PATH), the buffer needs to cater for that.

For C++ (as originally tagged), an alternative is to use std::basic_string<TCHAR> and then the operator+ (or +=) as per usual. The .c_str() will get you the resultant string;

std::basic_string<TCHAR> buffer(pszSourceFile);
buffer += TEXT(".txt");
auto ptr = buffer.c_str();
Niall
  • 30,036
  • 10
  • 99
  • 142
  • Thanks for you comment, but it gives me the error: 'wcscat': This function or variable may be unsafe. Consider using wcscat_s instead. – De Fix May 17 '16 at 13:26
  • Yes, Windows included a number of more secure versions (MS specific, the warnings can be turned off), you can use those alternatives as well, they will need a length indicator to get to compile and run correctly. – Niall May 17 '16 at 13:27
  • @DeFix. If you found one of the answers most useful or correct, you should consider accepting it. – Niall May 17 '16 at 16:49
0

Your particular use case is not a simple "append" but rather an insert/format. Along the same lines as Niall you are using the TCHAR macros so I would recommend _stprintf_s (or _sntprintf_s... see MSDN)

TCHAR output[SIZE] = {0};
_stprintf_s(output, _T("The %s directory"), pszSourceFile);

Of course it depends on what exactly pszSourceFile is... if it is a std::string then you'll need to use the c_str() member to get a pointer, and you'll need to be careful about using std::string versus std::wstring.

Dennis
  • 3,683
  • 1
  • 21
  • 43