将字符串添加到LPTSTR

时间:2016-05-17 13:11:06

标签: c winapi

我想在LPTSTR中添加一个字符串。

代码是:

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);
}

pszSourceFile是一种LPTSTR,但我想添加一些额外的文本。

喜欢(不工作)

  

pszSourceFile +" .txt"

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

考虑C风格和使用Windows API(使用TEXT() et.al.);使用_tcscat()_tcsncat()(后者需要缓冲区大小)。

例如;

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

Demo

警告的;注意你的缓冲区溢出。假设“正常”的Windows 260字符路径文件和名称限制(_MAX_PATH),缓冲区需要满足。

对于C ++(最初标记的),另一种方法是使用std::basic_string<TCHAR>,然后按照惯例使用operator+(或+=)。 .c_str()会得到结果字符串;

std::basic_string<TCHAR> buffer(pszSourceFile);
buffer += TEXT(".txt");
auto ptr = buffer.c_str();

答案 1 :(得分:0)

您的特定用例不是简单的“附加”,而是插入/格式。与Niall一样,您使用TCHAR宏,因此我建议使用_stprintf_s(或_sntprintf_s ...查看MSDN

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

当然这取决于pszSourceFile到底是什么......如果它是std::string那么你需要使用c_str()成员来获取指针,而你'在使用std::stringstd::wstring时需要注意。