fscanf Function

Scans formatted text from a stream.

Include

<stdio.h>

Prototype

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

Arguments

stream pointer to the open stream from which to read data
format format control string
... optional arguments

Return Value

Returns the number of items successfully converted and assigned. If no items are assigned, a 0 is returned. EOF is returned if end-of-file is encountered before the first conversion or if an error occurs.

Remarks

The format argument has the same syntax and use that it has in scanf.

Example

#include <stdio.h> /* for fopen, fscanf,   */
                   /* fclose, fprintf,     */
                   /* fseek, printf, FILE, */
                   /* NULL, SEEK_SET       */

int main(void)
{
  FILE *myfile;
  char s[30];
  int x;
  char a;
  if ((myfile = fopen("afile", "w+")) == NULL)
    printf("Cannot open afile\n");
  else
  {
    fprintf(myfile, "%s %d times%c", 
            "Print this string", 100, '\n');

    fseek(myfile, 0L, SEEK_SET);

    fscanf(myfile, "%s", s);
    printf("%s\n", s);
    fscanf(myfile, "%s", s);
    printf("%s\n", s);
    fscanf(myfile, "%s", s);
    printf("%s\n", s);
    fscanf(myfile, "%d", &x);
    printf("%d\n", x);
    fscanf(myfile, "%s", s);
    printf("%s\n", s);
    fscanf(myfile, "%c", a);
    printf("%c\n", a);

    fclose(myfile);
  }
}

Example Input

Contents of afile:

Print this string 100 times

Example Output

Print
this
string
100
times