Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

fscanf — C23 stream function

`fscanf(stream, format, ...)` from `<stdio.h>` reads characters from a stream under format directives and stores converted results through successive pointer arguments. It returns the number of assignments performed, or `EOF` when an input failure occurs before the first conversion.

Version: C23

Syntax

int fscanf(FILE * restrict stream, const char * restrict format, ...);

fscanf(stream, format, ...) from <stdio.h> reads characters from a stream under format directives and stores converted results through successive pointer arguments. It returns the number of assignments performed, or EOF when an input failure occurs before the first conversion.

The example writes 7 2.50 blue to a temporary file and scans it with "%d %lf %4s" into an int, a double, and a five-element char array. Output 3 7 2.50 blue confirms three assignments and the bounded string conversion.

A matching failure before any assignment returns 0, whereas end-of-file or a read error before conversion returns EOF; %n does not increase the count. Every pointer type must exactly match its conversion. Give %s and %[ a width no greater than capacity minus one, or overflow and undefined behavior can result.

Examples

#include <stdio.h>
int main(void){FILE *stream=tmpfile();if(!stream)return 1;if(fputs("7 2.50 blue",stream)==EOF){fclose(stream);return 1;}rewind(stream);int count=0,number=0;double price=0.0;char color[5]={0};count=fscanf(stream,"%d %lf %4s",&number,&price,color);printf("%d %d %.2f %s\n",count,number,price,color);return fclose(stream)==0?0:1;}

Result

3 7 2.50 blue

The example writes `7 2.50 blue` to a temporary file and scans it with `"%d %lf %4s"` into an `int`, a `double`, and a five-element `char` array. Output `3 7 2.50 blue` confirms three assignments and the bounded string conversion.

Sources