Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is fwscanf_s() in C?

Kainat Asif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

fwscanf_s() reads a formatted string from an input stream and validates the arguments at runtime before printing them. The declaration for fwscanf_s() is shown below:

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

Note: The fwscanf_s function is not supported by some compilers. If a compiler supports fwscanf_s, the value of STDC_WANT_LIB_EXT1 is set to 1.

Parameters

  • stream: Pointer to the input stream from where input is to be read.
  • format: White character string where data is written.
  • ...(additional arguments): If format consists of format specifiers (e.g., %s, %d, …), the additional arguments consist of the strings where data is read.

Return value

The fwscanf_s() function returns the number of characters read from the input stream if the data is read successfully. A negative value is returned if there is an error when reading from the input stream.

Note: The return value of fwscanf_s() does not count terminating null characters.

Example

Consider the code snippet below, which demonstrates the use of fwscanf_s():

main.c
fwscanfExample.txt
#include <stdio.h>
#include <wchar.h>
int main() {
wchar_t buffer[80];
FILE* fPointer = fopen("fwscanfExample.txt", "r");
while(fwscanf_s(fPointer, L"%ls", buffer) > 0){
fwprintf(stdout, L"%S ",buffer);
}
fclose(fPointer);
return 0;
}

Output

This is fwscanf_s() Example code. 

Explanation

The fopen() function is used in line 8 to open the file for reading. The fwscanf_s()() function is used in line 10 to read from the file and write to buffer, which is created in line 6.

Note: The function above is not supported by the GCC compiler, hence you will get an implicit declaration of function fwscanf_s error. Use the following variant to get the job done: int fwscanf( FILE *stream, const wchar_t *format, ...);.

RELATED TAGS

c

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring