Book
Collection
Click for Table of Contents
© 2025 by Rance D. Necaise
C Primer for Python Programmers
Copyright © 2025
Rance D. Necaise

6.8 Binary Files

A binary file contains a sequence of binary numbers representing data values as they would be stored in the computer's memory. For example, if we want to store the value 12 in a binary file, it would be written as a binary value using 4-bytes or 32 bits,

00000000000000000000000000001100

the same as it would be stored in memory. In a text file, the ASCII code 52 would be stored in the file to represent the character 4.

Examples of binary files include those created by word processors, spreadsheet applications, and databases. Binary files cannot be read and displayed in text editors since they contain byte values outside the printable range.

Reading Binary Data

Sometimes you may need to process binary files, however. To read data from a binary file, you must know the format of the file in terms of what type of data is stored in the file and in what order. C provides a separate function for reading and writing binary data, the fread and fwrite functions.

Consider the following code segment

  1.   int num;
  2.   float avg;
  3.   char ch;
  4.  
  5.   fread(&num, sizeof(int), 1, infile);  
  6.   fread(&avg, sizeof(float), 1, infile);
  7.   fread(&ch, sizeof(char), 1, infile);

The fread function takes four arguments:

  • destination variable - the location where the value is to be stored.
  • data size - the size of the data value being read. This is typically indicated using the sizeof function.
  • number of elements - the number of instances of the data value to be read. This is value is typically 1 when reading a single value or a larger value when using an array.
  • input file - the input file variable.

The feof function can also be used with binary files to determine if the end of file was reached.

Note
Note

The sizeof function is a built-in function that returns the number of bytes used to store a given data type or the number of bytes that is allocated to a variable. For example,

  1. int count = 0;
  2. int size1;
  3. int size2;
  4.  
  5. size1 = sizeof(int);   // <-- returns 4 since an int requires 4 bytes.
  6. size2 = sizeof(count); // <-- returns 4 since count is an int variable.

Writing Binary Data

You can also create a binary file using the fwrite function to write the binary data to the file.

  1.   fwrite(&num, sizeof(int), 1, outfile);  

The fwrite function also takes arguments:

  • source variable - the location of the value to be written.
  • data size - the size of the data value being written. This is typically indicated using the sizeof function.
  • number of elements - the number of instances of the data value to be written. This is value is typically 1 when writing a single value or a larger value when using an array.
  • output file - the output file variable.