Binary Files in C programming
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Binary Files in C Programming: Read and Write Techniques

๐Ÿ“‘ On this page:
  • What is a Binary File?
  • Advantages of Binary Files
  • Quick Start Example
  • Binary File Opening Modes
  • Writing Data (fwrite)
  • Reading Data (fread)
  • Frequently Asked Questions
๐Ÿ“š In this tutorial, you will learn:
  • What binary files are and why they matter in C
  • The key differences between text and binary files
  • How to open binary files using fopen() with binary modes
  • How to write binary data using fwrite() with a real employee record example
  • How to read binary files using fread() step by step

What is a Binary File in C?

A binary file stores data in a format that computers can read directlyโ€”it's not meant to be human-readable. Unlike text files that store characters (like letters and numbers), binary files store data in raw binary format (0s and 1s).

๐Ÿ’ก Think of it this way: A text file is like a written note you can read. A binary file is like a QR codeโ€”only computers can understand it.

Text Files vs Binary Files: What's the Difference?

Feature Text Files Binary Files
Human-readableโœ… YesโŒ No
File sizeLargerSmaller
Read/write speedSlowerFaster
Can store complex dataโŒ Noโœ… Yes
Can be edited in Notepadโœ… YesโŒ No (garbage chars)

Why Use Binary Files in C?

1. Faster I/O Operations โ€” No conversion between text and binary

2. More Compact Storage โ€” Takes less disk space

3. Store Complex Data โ€” Structures, arrays, images, audio

4. Better Security โ€” Not easily readable by humans

๐Ÿš€ Quick Start: Complete Binary File Example

Now that you understand what binary files are, here's a complete, runnable example:

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp;
    int data = 12345;
    int read_data;

    // Write binary data
    fp = fopen("data.bin", "wb");
    if (fp == NULL) {
        printf("Error opening file for writing!\n");
        return 1;
    }
    fwrite(&data, sizeof(int), 1, fp);
    fclose(fp);

    // Read binary data
    fp = fopen("data.bin", "rb");
    if (fp == NULL) {
        printf("Error opening file for reading!\n");
        return 1;
    }
    fread(&read_data, sizeof(int), 1, fp);
    fclose(fp);

    printf("Original: %d\nRead back: %d\n", data, read_data);
    return 0;
}
                                    

Expected Output:

Original: 12345
Read back: 12345
                                    

โœ… What just happened? The program stored the number 12345 in a binary file, then read it back. You can't see the data in a text editor, but the computer understands it perfectly!

How to Read and Write Binary Files in C

Binary files in C are like arrays, but instead of temporary storage in memory, they enable permanent storage on disk. Unlike text files, binary files let you read, write, and search data from any position, making them perfect for handling large or complex data such as images, audio, or video.

Why Should You Use Binary Files in C?

  • Faster Input/Output Operations: Since binary files store data in its raw form, you avoid the overhead of converting data to and from text, which speeds up processing, especially with large datasets.
  • More Compact Storage: Binary files take up less space, which is crucial when working with multimedia files or storing vast amounts of data.
  • Handling Raw Data: Some data, like compiled code or complex structures, cannot be easily converted to plain text, making binary files the preferred choice.

Understanding Binary File Opening Modes in C

In C, you can open binary files in different modes depending on your needs:

rb: Open for reading only in binary mode.

wb+: Open for reading and writing; creates a new file or clears existing file content.

wb: Open for writing only; creates or overwrites an existing file.

ab+: Open for appending (reading and writing); creates file if it doesn't exist.

rb+: Open for both reading and writing.

ab: Append data to the end of the file; creates if not exists.

Writing Data to a Binary File in C

To write data into a binary file in C, you typically use the fwrite() function:

fwrite(pointerToData, sizeOfData, numberOfItems, filePointer);

This function takes four parameters:

pointerToData: The address of the data you want to write.

sizeOfData: The size in bytes of each data item.

numberOfItems: How many data items you want to write.

filePointer: The pointer to the open file.


How to Write Employee Data to a Binary File in C Using fwrite()

Learn how to efficiently store employee records in a binary file in C using the fwrite() function. Writing data in binary format allows for fast, compact storage of complex data structures like employee information, including employee number, salary, and bonus.

#include <stdio.h>
#include <stdlib.h>

// Define the employee structure
struct employee {
    int empno;
    int salary;
    float bonus;
};

int main() {
    int n;
    struct employee e1;
    FILE *fptr;

    // Open the binary file for writing
    if ((fptr = fopen("employee.bin", "wb")) == NULL) {
        printf("Error! Unable to open file.\n");
        exit(1);
    }

    // Generate and write employee data to the binary file
    for (n = 1900; n < 1905; ++n) {
        e1.empno = n;
        e1.salary = 5 * n;
        e1.bonus = e1.salary * 0.10;

        // Write the employee data to the binary file
        fwrite(&e1, sizeof(struct employee), 1, fptr);
    }

    // Close the file after writing
    fclose(fptr);
    return 0;
}

This program creates a binary file named employee.bin in your project directory. It defines an employee structure with three members: empno, salary, and bonus. Inside the for loop, it populates this structure with sample data and writes each record to the binary file using fwrite(). The data is stored efficiently in binary format, making it suitable for applications requiring fast data access and minimal storage space.

In this example, the program creates a new file called employee.bin. The employee structure holds employee number, salary, and bonus. The fwrite() function takes the address of e1, the size of the structure, the number of items to write (1 in this case), and the file pointer fptr. After writing all records, the file is closed with fclose().

๐Ÿ’ป Practice Exercise

Challenge: Create a program that writes 10 integer values (1 to 10) to a binary file and then reads them back. Use a loop with fwrite() and fread().

๐Ÿ” Click to Show Solution
#include <stdio.h>

int main() {
    FILE *fp;
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int read_arr[10];

    // Write array to binary file
    fp = fopen("numbers.bin", "wb");
    if (fp == NULL) {
        printf("Error opening file for writing!\n");
        return 1;
    }
    fwrite(arr, sizeof(int), 10, fp);
    fclose(fp);

    // Read array from binary file
    fp = fopen("numbers.bin", "rb");
    if (fp == NULL) {
        printf("Error opening file for reading!\n");
        return 1;
    }
    fread(read_arr, sizeof(int), 10, fp);
    fclose(fp);

    // Display read data
    printf("Numbers read from binary file:\n");
    for (int i = 0; i < 10; i++) {
        printf("%d ", read_arr[i]);
    }
    printf("\n");
    return 0;
}
                                    

Expected Output:

Numbers read from binary file:
1 2 3 4 5 6 7 8 9 10
                                    

Reading Data from a Binary File in C Using fread()

Learn how to read employee records from a binary file in C using the fread() function. This function allows you to efficiently retrieve data stored in binary format, such as structures containing employee information.

Example: Reading Employee Data from a Binary File in C with fread()

#include <stdio.h>
#include <stdlib.h>

// Define the employee structure
typedef struct {
    int empno;
    int salary;
    float bonus;
} employee;

int main() {
    // Open the binary file in read mode
    FILE* file = fopen("employee.bin", "rb");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    // Declare a structure variable to hold read data
    employee e1;

    // Read employee records one by one until end of file
    while (fread(&e1, sizeof(employee), 1, file) == 1) {
        // Process the read data (e.g., print)
        printf("Employee No: %d, Salary: %d, Bonus: %.2f\n", e1.empno, e1.salary, e1.bonus);
    }

    // Close the file
    fclose(file);
    return 0;
}

In this program, the file employee.bin is opened in binary read mode ("rb"). The program reads each employee record into the employee structure variable e1 using fread(). The loop continues until all records are read, allowing you to process or display the employee information as needed.


Frequently Asked Questions About Binary Files in C

1. What is the difference between text and binary files in C?

Text files store data as human-readable characters (ASCII), while binary files store data in raw binary format. Binary files are more compact, faster to read/write, and can store complex data structures directly. However, text files are easier to debug and view with any text editor.

2. Can I mix text and binary operations on the same file?

No, you should never mix text and binary operations on the same file. Always use the correct mode consistentlyโ€”use "rb" and "wb" for binary files, and "r" and "w" for text files. Mixing modes can lead to data corruption and undefined behavior.

3. Why does my binary file contain non-printable characters?

Binary files store data in machine-readable formatโ€”they're not meant to be viewed as text. The "garbage" or "non-printable" characters you see are actually the raw binary data (1s and 0s) displayed as characters. This is normal and expected behavior.

4. Why should I use fwrite() instead of fprintf()?

fwrite() writes raw binary data directly, which is faster and more compact. fprintf() converts data to text format, which is slower and takes more space. Use fwrite() for binary files and fprintf() for text files.

5. What happens if I open a binary file in text mode?

Opening a binary file in text mode ("r" or "w") can corrupt the data. On Windows, text mode converts newline characters (\r\n to \n), which can corrupt binary data. Always use "rb" and "wb" for binary files.

๐Ÿ’ก Tip: Always check return values of fopen(), fread(), and fwrite() to handle errors gracefully.

๐Ÿ“– Related Tutorials

  • File Handling in C - Complete Guide
  • File Handling Examples in C
  • Count Words and Lines in a File
  • Copy Files in C

Previous Topic: -->> files examples in C   ||   Next topic: -->> Count word line in file


๐Ÿ“š Explore More Topics

๐Ÿ—„๏ธ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

๐Ÿ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

โ˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.