C++ fgetws()

The fgetws() function in C++ reads a specified maximum number of wide characters from the given file stream.

The fgetws() function is defined in <cwchar> header file.

fgetws() prototype

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

The fgetws() function reads a maximum of count-1 wide characters from the given file stream i.e. stream and stores them in the array pointed to by str.

The parsing stops if the end of file occurs or a newline character (\n) is found before reading (count-1) wide characters. The array str will contain the newline wide character in case it is found.


fgetws() Parameters

  • str: Pointer to an wide character array that stores the content of file.
  • count: Maximum number of wide characters to write.
  • stream: The file stream to read the wide characters.

fgetws() Return value

On success, the fgetws() function returns str and on failure it returns null pointer.


Example: How fgetws() function works?

#include <iostream>
#include <cwchar>
#include <cstdio>
#include <clocale>
using namespace std;

int main()
{
	setlocale(LC_ALL, "en_US.UTF-8");
	wchar_t line1[] = L"Hëĺĺo Everɏbȍdy\n";
	wchar_t line2[] = L"C++ ċăn haʼnđle tĥeșë veɍƴ ŵeįrd čhāråcŧerƨ\n";
	wchar_t data[20];

	FILE *fp = fopen("file.txt","r+");
	fputws(line1, fp);
	fputws(line2, fp);
	rewind(fp);

	while(true)
	{
		fgetws(data, 20, fp);
		if(!feof(fp))
			wcout << data << endl;
		else
			break;
	}

	fclose(fp);
	return 0;
}

When you run the program, a possible output will be:

Hëĺĺo Everɏbȍdy
C++ ċăn haʼnđle tĥeș
ë veɍƴ ŵeįrd čhāråc
ŧerƨ
Did you find this article helpful?