fscanf() can read records containing multiple fields by supplying to the second argument a series of type specifiers for each field in the record. - C File

C examples for File:Binary File

Introduction

For example, the next fscanf() function expects to read two character strings called name and hobby.

fscanf(pRead, "%s%s", name, hobby); 

%s type specifier will read a series of characters until a white space is found, including blank, new line, or tab.

The following table lists the type specifiers you can use with the fscanf() function.

Type Description
cSingle character
dDecimal integer
e, E, f, g, GFloating point
oOctal integer
sString of characters
uUnsigned decimal integer
x, X Hexadecimal integer

Demo Code

#include <stdio.h> 
int main() { //from w w w  .  j  a  va 2 s  .  c om
   FILE *pRead; 
   char name[10]; 
   char hobby[15]; 
   pRead = fopen("hobbies.dat", "r"); 
   if ( pRead == NULL ) 
      printf("\nFile cannot be opened\n"); 
   else 
      printf("\nName\tHobby\n\n"); 
   fscanf(pRead, "%s%s", name, hobby); 
   while ( !feof(pRead) ) {
        printf("%s\t%s\n", name, hobby); 
        fscanf(pRead, "%s%s", name, hobby); 
   }  //end loop 
}

Result


Related Tutorials