fread and fwrite in c

fread and fwrite functions are used to read and write binary files.

Writing to a binary file ,we should use fwrite() functions,this argument takes four arguments

fwrite():

this function is used to write block of data (structures or arrays ) into a file.

syntax:

fwrite(const void *ptr, size_t size, size_t n, FILE *fp);
  • the variable must be array or structure
  • ptr points to the block of the memory where data needs to be written
  • size specifies the number of bytes to be written
  • n is the number of items to be written
  • fp is the pointer to the file , where data needs to be written

example:

#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","wb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, *fptr);
}
fclose(fptr);
return 0;
}

fread():

this function is used to read block of data (structures or arrays ) from a file.

fread(void *ptr, size_t size, size_t n, FILE *fp);
  • ptr has staring memory address,so the data will be stored after reading
  • size specifies the number of bytes to read
  • n is the number of items to be read
  • fp is the pointer to the file