Example (fscanf -- Read Formatted Data)

This example opens the file myfile.dat for reading and then scans this file for a string, a long integer value, a character, and a floating-point value.

#include <stdio.h>
#define FILENAME "myfile.dat"
#define  MAX_LEN  80
int main(void)
{
   FILE *stream;
   long l;
   float fp;
   char s[MAX_LEN + 1];
   char c;
   stream = fopen("FILENAME", "r");
   /* Put in various data. */
   fscanf(stream, "%s", &s[0]);
   fscanf(stream, "%ld", &l);
   fscanf(stream, "%c", &c);
   fscanf(stream, "%f", &fp);
   printf("string = %s\n", s);
   printf("long double = %ld\n", l);
   printf("char = %c\n", c);
   printf("float = %f\n", fp);
   return 0;
   /******************************************************
      If FILENAME contains:
      abcdefghijklmnopqrstuvwxyz 343.2,
      the output should be:
      string = abcdefghijklmnopqrstuvwxyz
      long double = 343
      char = .
      float = 2.000000
   *******************************************************/
}