Append extra null char to wide string

1.1k views Asked by At

Some Win32 API structures require to concatenate an extra null character to a string, as in the following example taken from here:

c:\temp1.txt'\0'c:\temp2.txt'\0''\0'

When it comes to wide strings, what is the easiest way to append a L'\0' to the end of an existing wide string?

Here's what works for me but seems too cumbersome:

wchar_t my_string[10] = L"abc";
size_t len = wcslen(my_string);
wchar_t nullchar[1] = {'\0'};
memcpy(my_string + len + 1, nullchar, sizeof(wchar_t));
4

There are 4 answers

1
gil_mo On BEST ANSWER

assuming my_string is long enough:

my_string[wcslen(my_string)+1]='\0';

The terminating null will be translated to a wide char.

(Posted as a first comment to the question)

1
tenfour On

In your example you can just assign the value just like any other array. There's nothing special about wchar_t here.

my_string already has a single null-termination, so if you want double null-termination, then just add another 0 after it.

wchar_t my_string[10] = L"abc";
size_t len = wcslen(my_string);
// todo: check out-of-bounds
my_string[len + 1] = 0;

Or even simpler, if it's really just a string literal,

wchar_t my_string[10] = L"abc\0";

This will be doubly-null-terminated.

0
Remy Lebeau On

If you use std::wstring instead of wchar_t[], you can use its operator+= to append the extra null terminator, eg:

wstring my_string = L"abc";
...
my_string += L'\0';
// use my_string.c_str() as needed...
0
Botje On

Assuming you have the various paths in a std::vector<std::wstring>, you can just build the required format in a loop:

std::vector<std::wstring> paths;
paths.emplace_back(L""); // This empty path will add the extra NUL
std::wstring buf(1000, 0);
for (auto p : paths) {
    buf.append(p);
    buf.append(1, 0);
}
wchar_t *ptr = buf.c_str(); // Now do stuff with it