Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf an LPCWSTR variable

Tags:

c++

windows

I'm trying to debug print an LPCWSTR string, but I get a problem during the sprintf push in the buffer, because it retrieves only the first character from the string.

Here is the code:

HANDLE WINAPI hookedCreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) {
    char buffer[1024];
    sprintf_s(buffer, 1024, "CreateFileW: %s", lpFileName);
    OutputDebugString(buffer); 
    return trueCreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwFlagsAndAttributes, dwCreationDisposition, hTemplateFile);
}

For example I get CreateFileW: C or CreateFileW: \.

How do I properly push it into the buffer?

Thank you.

like image 599
Julio Avatar asked Jun 14 '10 14:06

Julio


People also ask

What is Lpcwstr?

An LPCWSTR is a 32-bit pointer to a constant string of 16-bit Unicode characters, which MAY be null-terminated.

What library is Sprintf in?

The C library function int sprintf(char *str, const char *format, ...) sends formatted output to a string pointed to, by str.


2 Answers

You need to tell sprintf() that you pass a wide character string. Use the %ls specifier:

 sprintf_s(buffer, 1024, "CreateFileW: %ls", lpFileName);

Do note how unproductive this is. Your code runs on a Unicode operating system. It must convert your char[] string back to a wide string before it can send it to the debugger. That's just wasted CPU cycles with a significant risk of data loss to boot. When you are in Rome, act like a Roman and use wchar_t + wsprintf(). And #define UNICODE so you'll automatically call the fast OutputDebugStringW(), the one that doesn't have to convert the string. The point of using C++ is to write fast code, intentionally making is slow is pointless.

like image 194
Hans Passant Avatar answered Oct 19 '22 11:10

Hans Passant


Use swprintf_s which is the version of sprintf_s which is designed for wide-character strings.

You'll also need an array of wchar_t instead of char and to use OutputDebugStringW()

Also, note you that swprintf_w might not be entierly what you want to call. If it encounters a string that is longer than the size you give it, it executes some sort of assertion. I suggest you test this situation specifically.

like image 39
shoosh Avatar answered Oct 19 '22 12:10

shoosh