a shot of dev knowledge

Related tags

What is fputwc in C?

The fputwc function in C is used to write a wide character to an output stream.

It is very similar to fputws, which is used to write a wide character string to an output stream.

We must include the stdio.h and wchar.h libraries in order to use the fputsw function and declare a wide character of type wchar_t.

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

Syntax

wint_t fputwc(
   wchar_t character, FILE *ptr );

Parameters

The fputsw function takes in two parameters:

  • character – This is the single wide character that is to be written to the specified stream
  • ptr – This is a pointer to an output stream to which the wide character will be written

Return value

If the fputcw function completes execution successfully, it returns the character written to the stream.

In case of an error, the fputcw function returns a value of WEOF. If the error was related to character encoding, errno would be set to EILSEQ. Otherwise, it may be concluded that the error was a write error.

To access errno, the errno.h library must be included, as shown here:

#include <errno.h>

Example

In the example below, we write a wide character to the stream stdout. We store the return value in a variable of type wint_t and perform error handling. If the value is equal to WEOF, we conclude that an error occurred and move to the nested if statement to check if it was an encoding error or write error.

However, since the function executes successfully in this example, the character written to the output stream is returned and printed onto the screen as expected:

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

int main()
{
    wint_t ret_val = fputwc(L'h', stdout);
    
    if (ret_val == WEOF) {
    
        if (errno == EILSEQ)
            puts("There was an error in encoding!");
        else
            puts("There was a write error!");
    }

    return 0;
    
}

Related tags

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring