What is fgetws in C ?

The fgetws function reads wide characters from the file stream given as input and stores them in a string provided in the arguments. Once the end of the file or line is reached, file reading stops. A terminating null character is appended at the end of the characters. To use this function, the wchar.h header file needs to be included as shown below:

#include <wchar.h>

Prototype

This function is written as follows:

wchar_t *fgetws( wchar_t *str, int count, FILE *stream ); 

Parameters

Parameter Description
str pointer to the wchar_t array in which the read string is written.
count the length of str i.e., the maximum characters that will be copied in str. As the last character is the null character, at most count-1 characters are read from the stream.
stream pointer to a FILE that identifies a stream from which the character is read.

Return Value

It returns str if it is executed successfully. Otherwise, it returns a null pointer.

Example

The following code shows the usage of fgetws function. It reads the first line or the first 20 characters of sampleFile.txt, depending on what comes first, stores them in str and displays them:

main.c
sampleFile.txt
#include <stdio.h>
#include <wchar.h>
int main()
{
FILE * thisFile;
wchar_t str [20];
thisFile = fopen ("sampleFile.txt" , "r");
if (thisFile != NULL)
{
if ( fgetws (str , 11 , thisFile) != NULL )
{
fputws ( str, stdout );
}
fclose (thisFile);
}
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved