C Standard Library

C <wchar.h> - fputwc() Function



The C <wchar.h> fputwc() function writes a wide character wc to the output stream stream and advances the position indicator. The wide character is written as a multibyte character in external files, as if wcrtomb() function is called to convert wc with the stream's internal mbstate_t object.

If the wide character cannot be represented using the multibyte encoding, the function returns WEOF and sets errno to EILSEQ.

If a writing error occurs, the function returns WEOF and sets the error indicator for the stream ferror().

fputwc() and putwc() are equivalent, except that putwc() may be implemented as a macro in some libraries.

Syntax

wint_t fputwc (wchar_t wc, FILE* stream);

Parameters

wc Specify a wide character to be written.
stream Specify a pointer to a FILE object that specifies an output stream.

Return Value

On success, the character wc is returned. On writing error, returns WEOF and sets the error indicator ferror(). On encoding error, returns WEOF and sets errno to EILSEQ.

Example:

In the example below, the file test.txt is opened in write mode.The program creates an empty file for output operations if the file does not exist. If the file already exists, its contents are discarded and the file is treated as a new empty file. Finally it writes ABCDEFGHIJKLMNOPQRSTUVWXYZ in the file before closing it.

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

int main (){
  //open the file in write mode
  FILE *pFile = fopen("test.txt", "w");
  
  //writes wide character in the file
  for(wchar_t wc = L'A'; wc <= L'Z'; wc++)
    fputwc(wc, pFile);

  //close the file
  fclose(pFile);

  //open the file in read mode to read
  //the content of the file
  pFile = fopen("test.txt", "r");
  wint_t wc = fgetwc(pFile);
  while (wc != WEOF) {
    putwchar(wc);
    wc = fgetwc(pFile);
  }

  //close the file
  fclose(pFile);
  return 0;
}

The output of the above code will be:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

❮ C <wchar.h> Library