fread() and fwrite() Function in C Programming

The fwrite() function

The fwrite() function is used to write records (sequence of bytes) to the file. A record may be an array or a structure.

Syntax

  fwrite( ptr, int size, int n, FILE *fp );
  • The fwrite() function takes four arguments.
  • ptr : ptr is the reference of an array or a structure stored in memory.
  • size : size is the total number of bytes to be written.
  • n : n is number of times a record will be written.
  • FILE* : FILE* is a file where the records will be written in binary mode.

Example:



Output:

 Enter Roll : 1
 Enter Name : Ashish
 Enter Marks : 78.53
 Do you want to add another data (y/n) : y
 Enter Roll : 2
 Enter Name : Kaushal
 Enter Marks : 72.65
 Do you want to add another data (y/n) : y
 Enter Roll : 3
 Enter Name : Vishwas
 Enter Marks : 82.65
 Do you want to add another data (y/n) : n
 Data written successfully...


The fread() function

The fread() function is used to read bytes form the file.

Syntax

  fread( ptr, int size, int n, FILE *fp );
  • The fread() function takes four arguments.
  • ptr : ptr is the reference of an array or a structure where data will be stored after reading.
  • size : size is the total number of bytes to be read from file.
  • n : n is number of times a record will be read.
  • FILE* : FILE* is a file where the records will be read.

Example:



Output:

 Roll     Name       Marks
 1         Ashish      78.53
 2         Kaushal    72.65
 3         Vishwas    82.65