What is fwscanf() in C?

fwscanf() reads data from stream and stores it in accordance with the format specified in the format string.

Prototype

int fwscanf (FILE* stream, const wchar_t* format, ...);

Parameters

  • FILE* stream: The pointer to the stream from which the data is read.
  • const wchar_t* format : This specifies how the data will be read from the stream.
  • ...(additional arguments): If the format string contains format specifiers, additional arguments corresponding to the specifiers can be given here.

Return Type

  • fwscanf() returns the number of characters read upon success. If the function fails, then the count returned can be less than the number of characters written or even zero. fwscanf() raises the feof flag if end of file is encountered while reading, or ferror if an error occurs.

Example

#include <stdio.h>
#include <wchar.h>
int main() {
wchar_t buffer[80];
//create an output file and write the contents to it
const wchar_t output[80] = L"This was read from file";
FILE* inputFile;
inputFile = fopen("Temp.txt", "w+");
fwprintf(inputFile, L"%S\n",output);
fclose(inputFile);
//read from file
inputFile = fopen("Temp.txt","r+");
while(fwscanf(inputFile, L"%ls", buffer) > 0){
fwprintf(stdout, L"%S ",buffer);
}
fwprintf(stdout, L"\n");
fclose(inputFile);
return 0;
}

Explanation

In the code above, we first create a file called Temp.txt and write the contents of the output array to it as shown below:

fwprintf(inputFile, L"%ls\n",output);

Here, the format specifier ā€œ%Sā€ represents wide string.

When reading from the file, we use a while loop to test if the fwscanf() has encountered the EOF character or not. If it encounters the EOF character, it returns a negative value or zero, which can be used to test the condition as follows:

while(fwscanf(inputFile, L"%ls", buffer) > 0)

Once the contents have been read from the file into the buffer array, we can print them using the fwprintf() function.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
šŸ† Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved