Binary File Functions in C Programming Language

The C file system includes two important functions: fread() and fwrite(). These functions can read and write any type of data, using any kind of representation. Their prototypes are:

size_t fread(void *buffer, size_t size, size_t num,FILE *fp);

size_t fwrite(void *buffer, size_t size, size_t num, FILE *fp);

The fread() function reads from the file associated with fpnum number of objects, each object size bytes long, into buffer pointed to by buffer. It returns the number of objects actually read. If this value is 0, no objects have been read, and either end of file has been encountered or an error has occurred. You can use feof() or ferror()to find out which. Their prototypes are:

int feof(FILE *fp);

int ferror(FILE *fp);

The feof() function returns non-0 if the file associated with fp has reached the end of file, otherwise it returns 0. This function works for both binary files and text files. The ferror() function returns non-0 if the file associated with fp has experienced an error, otherwise it returns 0.

The fwrite() function is the opposite of fread(). It writes to file associated with fpnum number of objects, each object size bytes long, from the buffer pointed to by buffer. It returns the number of objects written. This value will be less than num only if an output error as occurred.
The void pointer is a pointer that can point to any type of data without the use of a TYPE cast (known as a generic pointer). The type size_t is a variable that is able to hold a value equal to the size of the largest object surported by the compiler. As a simple example, this program write an integer value to a file called MYFILE using its internal, binary representation.

#include <stdio.h> /* header file */

#include <stdlib.h>

void main(void)

{

FILE *fp; /* file pointer */

int i;

/* open file for output */

if ((fp = fopen("myfile", "w"))==NULL){

printf("Cannot open file \n");

exit(1);

}

i=100;

if (fwrite(&i, 2, 1, fp) !=1){

printf("Write error occurred");

exit(1);

}

fclose(fp);

/* open file for input */

if ((fp =fopen("myfile", "r"))==NULL){

printf("Read error occurred");

exit(1);

}

printf("i is %d",i);

fclose(fp);

}


Learn More :