Append Data to a Binary File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Append Data to an Existing Binary File

In this tutorial, you'll learn how to append data to an existing binary file using the C programming language. Binary files store raw bytes — structs, images, audio, and other non-text data — and appending to them is a common operation when you maintain a growing database of records. The key is opening the file in "ab" mode, which preserves the existing content and positions the file pointer at the very end so new data is written after what's already there.

C program to append data to an existing binary file using fopen ab mode and fwrite, with step-by-step explanation.

📝 Problem Statement

Write a program in C to append data to an existing binary file.

⚙️ How the Program Works

The program uses a structure to represent a record (for example, a student), opens the file in append-binary mode, and writes the new record at the end of the file:

  1. Define a struct that represents the type of record stored in the file.
  2. Prompt for the new record and fill the struct fields.
  3. Open the file with fopen("records.bin", "ab"). The "ab" mode opens for appending in binary — creating the file if it doesn't exist.
  4. Check for NULL in case the file cannot be opened.
  5. Write with fwrite() to append the struct's bytes to the end of the file.
  6. Close the file with fclose() to flush the data to disk.

💻 Complete C Program

#include <stdio.h> #include <string.h> struct Student { int id; char name[50]; float marks; }; int main(void) { FILE *fp; struct Student s; /* Read the new record from the user */ printf("Enter student ID: "); scanf("%d", &s.id); printf("Enter student name: "); scanf(" %49[^\n]", s.name); printf("Enter marks: "); scanf("%f", &s.marks); /* Open the binary file in append mode. "ab" = append + binary. Creates the file if it does not exist; otherwise writes at the end. */ fp = fopen("records.bin", "ab"); if (fp == NULL) { printf("Error: Could not open records.bin for appending.\n"); return 1; } /* Append one full struct to the file */ fwrite(&s, sizeof(struct Student), 1, fp); fclose(fp); printf("Record appended to records.bin successfully.\n"); return 0; }

🖥️ Sample Output

First run — the file records.bin does not exist yet, so "ab" creates it:

Console (first run): Enter student ID: 101
Enter student name: Alice
Enter marks: 87.5
Record appended to records.bin successfully.

Second run — the file already exists, so the new record is added after the first:

Console (second run): Enter student ID: 102
Enter student name: Bob
Enter marks: 91.0
Record appended to records.bin successfully.

After both runs, records.bin contains two Student records back-to-back — Alice first, then Bob. Reading them requires a matching fread loop (see Assignment 8).

🔍 Line-by-Line Explanation

Line / Code Explanation
struct Student { ... }; Defines the record layout that will be stored in the binary file. Both writer and reader must use the same struct.
fopen("records.bin", "ab") Opens for appending in binary. Existing content is preserved, and all writes go to the end of the file.
if (fp == NULL) Detects failure — for example, a permission problem or a full disk.
fwrite(&s, sizeof(struct Student), 1, fp) Writes one full struct (sizeof bytes) to the file. The first argument is a pointer to the data, the second is the element size, the third is the count, and the fourth is the file pointer.
fclose(fp) Flushes buffered bytes to disk and releases the file handle.

📂 Why "ab" Instead of "wb"

Both "ab" and "wb" open a file for binary writing, but they behave very differently on existing files:

Mode Meaning Creates file? Erases existing content? Write position
"wb" Write binary Yes Yes — truncates to 0 bytes Start of file
"ab" Append binary Yes No End of file
"rb" Read binary No No Read only
"ab+" Append and read Yes No End of file (for writes)
⚠️ Important: Using "wb" on a file that already contains records will erase everything. Always use "ab" when you want to add records without losing existing data.

🐛 Common Pitfalls

  • Missing b in the mode: On Windows, text mode translates \n and EOF characters. Binary data must be read and written in binary mode or the bytes will be corrupted.
  • Forgetting to check fopen: An unchecked NULL pointer will crash the program on the first fwrite.
  • Ignoring fwrite's return value: It returns the number of items successfully written. If it's less than the requested count, the disk may be full.
  • Struct layout mismatch: If the writer and reader use different struct definitions (different field types or order), the binary data will be unreadable. Keep the struct in a shared header file when possible.
  • Pointers inside structs: Never store a pointer field inside a struct that gets written to disk — pointers are process-specific and meaningless when read back.

💡 Tips & Best Practices

  • Use "ab" to append, "rb" to read, and "rb+" to read and modify existing records.
  • Store the struct count somewhere (a separate header, or as a magic number at the start of the file) so the reader knows how many records to expect.
  • On Linux and Windows the binary layout of int and float may differ. For cross-platform files, serialize fields one by one with fwrite on each field instead of dumping the whole struct.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch type and size warnings.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 7. Write Data to a Binary File
  • 8. Read Binary Data from a Binary File and Display It
  • 16. Store and Retrieve Student Records Using Structures and Binary Files
  • Binary Files in C — Overview
  • Files FAQ

Previous Problem: -->> 2. Search for a Specific Word in a Text File   ||   Next Problem: -->> 4. Read and Display the Contents of a Text File

Back to Index: -->> File Handling Assignments in C


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 Processiong
    • 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.