1

I'm trying to write a message containing "alpha = abcd" to a text file using the following code:

#include <stdio.h>
#include <wchar.h>

int
main()
{
        const wchar_t *a = L"abcd", *msg = L"alpha = %s\n";
        FILE          *f = fopen("./deleteme", "a");

        fwprintf(f, msg, a);
        fclose(f);
}

However, after compiling and executing the program I get this output instead:

alpha = a

Why only the first character from the const a gets copied to output?

user6039980
  • 3,108
  • 8
  • 31
  • 57

2 Answers2

2

You need to change:

L"alpha = %s\n";

to:

L"alpha = %S\n";

The argument (a = L"abcd") you are trying to print is a wide string, and therefore you need %S (uppercase) instead of %s (lowercase). Using incorrect format specifiers for printf-like functions is undefined behaviour.

Read the documentation for printf format specifiers.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
1

With a C99 compliant compiler , use "%ls".

If an l length modifier is present, the argument shall be a pointer to the initial element of an array of wchar_t type. C11dr §7.29.2.1 10.

// const wchar_t *msg = L"alpha = %s\n";
const wchar_t *msg = L"alpha = %ls\n";
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256