Binary Input Output Function in C

binary I/O functions

In an earlier tutorial we talked about file I/O functions and the use of text files. In this C programming tutorial we are going to talk about the use of binary files.

Binary files

Binary files are very similar to arrays of structures, except the structures are in a disk-file rather than an array in memory. Binary files have two features that distinguish them from text files:

  • You can instantly use any structure in the file.
  • You can change the contents of a structure anywhere in the file.

After you have opened the binary file, you can read and write a structure or seek a specific position in the file. A file position indicator points to record 0 when the file is opened.

A read operation reads the structure where the file position indicator is pointing to. After reading the structure the pointer is moved to point at the next structure.

A write operation will write to the currently pointed-to structure. After the write operation the file position indicator is moved to point at the next structure.

The fread and fwrite function takes four parameters:

  • A memory address.
  • Number of bytes to read per block.
  • Number of blocks to read.
  • A file variable.

Example: