fscanf - C stdio.h

C examples for stdio.h:fscanf

Type

function

From


<cstdio>
<stdio.h>

Description

Read formatted data from stream

Prototype

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

Parameters

ParameterDescription
stream FILE object.
format format string

format string can have the following value.

For whitespace character, fscanf will read and ignore any whitespace characters encountered before the next non-whitespace character.

A single whitespace in the format string marks any quantity of whitespace characters extracted from the stream.

Non-whitespace character, except format specifier (%) is discarded and the function continues.

Format specifiers have the following prototype:

%[*][width][length]specifier Where the
specifierDescription<th>Characters extracted</th>
i, uIntegerdigits, optionally preceded by a sign (+ or -). Decimal digits assumed by default (0-9), but a 0 prefix introduces octal digits (0-7), and 0x hexadecimal digits (0-f).
dDecimal integerdecimal digits (0-9), optionally preceded by a sign (+ or -).
oOctal integeroctal digits (0-7), optionally preceded by a sign (+ or -).
xHexadecimal integerhexadecimal digits (0-9, a-f, A-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -).
f, e, gFloating point numberdecimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer.
cCharacterThe next character.
sString of charactersAny number of non-whitespace characters, stopping at the first whitespace character found.
pPointer addressA sequence of characters representing a pointer.
[characters]Scansetonly read the characters specified between the brackets.
[^characters]Negated scansetnot read the characters specified between the brackets.
nCountNo input is consumed. The number of characters read so far is saved in the signed int.
%%A % followed by another % matches a single %.
sub-specifierdescription
*asterisk indicates that the data is to be read from the stream but ignored.
widthset the maximum number of characters to be read.
lengthOne of hh, h, l, ll, j, z, t, L (optional).

Return Value

On success, the function returns the number of items of the argument list filled.

If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.

Example

This sample code creates a file called main.cpp and writes a float number and a string.

The stream is rewinded and both values are read with fscanf.

Demo Code


#include <stdio.h>

int main ()/*from  ww w  . jav  a  2  s.c  om*/
{
  char str [80];
  float f;
  FILE * pFile;

  pFile = fopen ("main.cpp","w+");
  fprintf (pFile, "%f %s", 3.1416, "PI");
  rewind (pFile);
  fscanf (pFile, "%f", &f);
  fscanf (pFile, "%s", str);
  fclose (pFile);
  printf ("I have read: %f and %s \n",f,str);
  return 0;
}

Related Tutorials