Monday, February 20, 2012

C Language - fscanf() : read formatted data from stream

fscanf

function
<cstdio>
int fscanf ( FILE * stream, const char * format, ... );
Read formatted data from stream
Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.

Parameters

stream
Pointer to a FILE object that identifies the stream to read data from.
format
C string that contains one or more of the following items:
  • Whitespace character: the function will read and ignore any whitespace characters (this includes blank spaces and the newline and tab characters) which are encountered before the next non-whitespace character. This includes any quantity of whitespace characters, or none.
  • Non-whitespace character, except percentage signs (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.
  • Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored in the locations pointed by the additional arguments. A format specifier follows this prototype:

    [=%[*][width][modifiers]type=]

    where:

    *An optional starting asterisk indicates that the data is to be read from the stream but ignored, i.e. it is not stored in the corresponding argument.
    widthSpecifies the maximum number of characters to be read in the current reading operation
    modifiersSpecifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data pointed by the corresponding additional argument:
    h : short int (for d, i and n), or unsigned short int (for o, u and x)
    l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g)
    L : long double (for e, f and g)
    typeA character specifying the type of data to be read and how it is expected to be read. See next table.

    fscanf type specifiers:
    typeQualifying InputType of argument
    cSingle character: Reads the next character. If a width different from 1 is specified, the function reads width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.char *
    dDecimal integer: Number optionally preceeded with a + or - sign.int *
    e,E,f,g,GFloating point: Decimal number containing a decimal point, optionally preceeded by a + or - sign and optionally folowed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4float *
    oOctal integer.int *
    sString of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).char *
    uUnsigned decimal integer.unsigned int *
    x,XHexadecimal integer.int *
additional arguments
The function expects a sequence of references as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order. For each format specifier in the format string that retrieves data, an additional argument should be specified. These arguments are expected to be references (pointers): if you want to store the result of a fscanf operation on a regular variable you should precede its identifier with the reference operator, i.e. an ampersand sign (&), like in:
int n; fscanf (stream,"%d",&n);

Return Value

On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure.
In the case of an input failure before any data could be successfully read, EOF is returned.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* fscanf example */
#include <stdio.h>

int main ()
{
  char str [80];
  float f;
  FILE * pFile;

  pFile = fopen ("myfile.txt","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;
}


This sample code creates a file called myfile.txt and writes a float number and a string to it. Then, the stream is rewinded and both values are read with fscanf. It finally produces an output similar to:

I have read: 3.141600 and PI

No comments:

Post a Comment