The wcsncpy_s
function in C copies a specified number of characters from a given wide string to another location.
If the number of characters to copy is less than the size of the destination string, the wcsncpy_s
function stops after writing the null-terminating character. If there is no null-terminating character in the source string, the wcsncpy_s
function automatically adds it to the destination string.
The process is illustrated below:
Note: A wide string is comprised of characters from the Unicode character set.
To use the wcsncpy_s
function, you will need to include the <wchar.h>
library in the program, as shown below:
#include <wchar.h>
The prototype of the wcsncpy_s
function is shown below:
errno_t *wcsncpy_s(wchar_t *dest, rsize_t numElements, const wchar_t *src, rsize_t count);
The wcsncpy_s
function takes the following objects as parameters:
dest
: the destination stringnumElements
: the size of the destination stringsrc
: the source stringcount
: the maximum number of characters to copy from src
to dest
The wcsncpy_s
function copies the specified number of characters from the src
string to the dest
string and returns if the operation is successful; otherwise, it returns a non-zero value and writes the null-terminating character to dest
.
The wcsncpy_s
function will raise an error in the following situations:
src
or dest
are null
pointers.numElements
or count
is .count
is greater than the size of the destination string. We can avoid this by giving the count
parameter a value of wcsncpy_s
will only copy the number of characters that the destination string can safely hold.src
and dest
strings overlap.The code below shows how the wcsncpy_s
function works in C:
#define __STDC_WANT_LIB_EXT1__ 1#include <stdio.h>#include <wchar.h>#include <string.h>int main() {// initializing stringswchar_t src[] = L"Learning with Educative";wchar_t dst[40];// copying stringwcsncpy_s(dst, 40, src, wcslen(src));return 0;}
First, two wide strings are initialized for the source and destination addresses. The ‘L’ identifier in line 8 informs the compiler that the Unicode character set is being used.
The wcsncpy_s
function proceeds to copy the entire source string to the destination address in line 12. The argument 40
specifies that the destination string can hold a maximum of characters. The wcslen
function finds the length of the source string so that the entire string is copied to dest
. After the src
string is copied, the wcsncpy_s
function appends a null-terminating character to dest
.
The GCC compiler does not support the function in the example above, so you will get an implicit declaration of function…
error. Use the following variant to get the job done:
wchar_t* wcsncpy(wchar_t* dest, const wchar_t* src, size_t n);
Free Resources