Printing computer name using GetComputerNameW

I am new to Windows APIs. I am doing an exercise on printing the computer name to the console. Here is the code I have so far:

wchar_t compName[MAX_COMPUTERNAME_LENGTH+1];
BOOL getName = GetComputerNameW(compName, &maxSize);

wprintf(L"Computer name is: %s",compName);

The issue is on the output. I only see Computer name is D on the console, when I should see DESKTOP-XXXXXX.

What am I doing wrong? I believe I am calling the right functions, per the MSDN docs. I have seen posts on StackOverflow regarding this issue, but it is in C++ and not C.

I feel like it has something to do with me printing a Unicode string.

>Solution :

The format specifier %s is for printing a string pointed at by char*, even in wprintf.

You should use format specifier %ls to print a string of wide characters.

printf, _printf_l, wprintf, _wprintf_l | Microsoft Learn

Leave a Reply