C examples for stdio.h:fscanf
function
<cstdio> <stdio.h>
Read formatted data from stream
int fscanf ( FILE * stream, const char * format, ... );
Parameter | Description |
---|---|
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
specifier | Description | <th>Characters extracted</th> |
---|---|---|
i, u | Integer | digits, 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). |
d | Decimal integer | decimal digits (0-9), optionally preceded by a sign (+ or -). |
o | Octal integer | octal digits (0-7), optionally preceded by a sign (+ or -). |
x | Hexadecimal integer | hexadecimal digits (0-9, a-f, A-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -). |
f, e, g | Floating point number | decimal 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. |
c | Character | The next character. |
s | String of characters | Any number of non-whitespace characters, stopping at the first whitespace character found. |
p | Pointer address | A sequence of characters representing a pointer. |
[characters] | Scanset | only read the characters specified between the brackets. |
[^characters] | Negated scanset | not read the characters specified between the brackets. |
n | Count | No input is consumed. The number of characters read so far is saved in the signed int. |
% | % | A % followed by another % matches a single %. |
sub-specifier | description |
---|---|
* | asterisk indicates that the data is to be read from the stream but ignored. |
width | set the maximum number of characters to be read. |
length | One of hh, h, l, ll, j, z, t, L (optional). |
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.
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.
#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; }