Writing Data to a file - C File

C examples for File:Binary File

Introduction

The fprintf() function takes a FILE pointer, a list of data types, and a list of values to write information to a data file.

Demo Code

#include <stdio.h> 
int main() { /*from  ww  w .  j a va2s .  com*/
   FILE *pWrite; 
   char fName[20]; 
   char lName[20]; 
   char id[15]; 
   float gpa; 
  
   pWrite = fopen("students.dat", "w"); 
   if ( pWrite == NULL ) 
      printf("\nFile not opened\n"); 
   else { 
      printf("\nEnter first name, last name, id and GPA\n\n"); 
      printf("Enter data separated by spaces: "); 

      scanf("%s%s%s%f", fName, lName, id, &gpa); 

      fprintf(pWrite, "%s\t%s\t%s\t%.2f\n", fName, lName, id, gpa); 
      fclose(pWrite); 
   }
}

Result


Related Tutorials