What is fputsw in C?

The fputsw function in C is used to write down the contents of a wide character string or array to a file stream. While the conventional character is of size 8 bits, the wide character is coded in 16 bits and simplifies the usage of international or larger coded character sets.

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

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

Syntax

int fputws(const wchar_t *char_array, FILE *file_ptr);

Parameters

The fputsw takes in two parameters:

  • char_array – This is a pointer to a wide character array that is to be written to a specified stream.
  • filename – This is a pointer to a FILE object or the stream to which we will write the wide character array.

Return value

If the write to the specified stream is successful, fputsw returns a non-negative integer.

In the case of a write error, it returns -1. However, if an encoding error occurs, which indicates an error in the conversion of wide characters to multi-byte characters, the function sets errno to EILSEQ and returns -1. We can access the variable errno by including the errno.h library:

#include <errno.h>

Example

In the code snippet below, we declare a pointer to a FILE object and a character of type wchar_t. We create and open a file to append the wide character string to it using fputsw. Once the string contents have been written to the file stream, we print it using the fgetc and printf functions:

#include <stdio.h>
#include <wchar.h>
#include <errno.h>
int main ()
{
//Declaration of FILE object, wchar_t string and file name
FILE * file_ptr_a;
wchar_t char_array [] = L"Welcome to Educative!";
char filename [] = "file.txt";
//Open file to write string to file stream
file_ptr_a = fopen (filename,"a");
int ret = fputws (char_array, file_ptr_a);
//Error handling
printf("Return value: %d\n", ret);
printf("Errno: %d\n", errno);
if (errno == EILSEQ)
{
printf("Conversion error!\n");
}
else if (ret == -1)
{
printf("Writing error!\n");
}
else
{
printf("fputsw executed successfully!\n");
}
//Close file after writing has been completed
fclose (file_ptr_a);
//Open file for printing contents
FILE* file_ptr_b = fopen(filename, "r");
//Using fgetc to fetch each character from stream
char c = fgetc(file_ptr_b);
while (c != EOF)
{
printf("%c", c);
c = fgetc(file_ptr_b);
}
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved