C++ Standard Library C++ STL Library

C++ <cwchar> - fgetws() Function



The C++ <cwchar> fgetws() function reads at most (num-1) characters from the given stream and stores them as a C wide string into ws. Parsing stops if a newline character is found, in which case ws will contain that newline character, or the end-of-file is reached.

A terminating null wide character is automatically appended after the characters copied to ws.

Syntax

wchar_t* fgetws (wchar_t* ws, int num, FILE* stream);

Parameters

ws Specify pointer to an array of wchar_t where the wide string read is copied.
num Specify maximum number of characters to be copied into ws.
stream Specify a pointer to a FILE object that specifies an input stream.

Return Value

  • On success, ws is returned, On failure, null pointer is returned.
  • If the failure has been caused due to end-of-file condition, additionally sets the end-of-file indicator feof() on stream. If this happens before any characters could be read, in which case a null pointer is returned and the contents of ws remains unchanged.
  • If error occurs due to some other reason, additionally sets the error indicator ferror() on stream.

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, file is opened using fopen() function in read mode. It reads first 15 wide characters from the file and prints them on screen.

#include <cstdio>
#include <cwchar>
 
int main (){
  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  wchar_t mystring [16];

  //read first 15 wide characters from the file
  if(fgetws(mystring, 16, pFile) != NULL)
    fputws (mystring, stdout);
  
  //close the file
  fclose(pFile);
  return 0;
}

The output of the above code will be:

This is a test 

❮ C++ <cwchar> Library