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

C Program to Write Data to a Binary File

In this tutorial, you'll learn how to write data to a binary file using the C programming language. Binary files store raw bytes — structs, arrays, images, audio, and other non-text data — without any character translation. The key function is fwrite(), and the key mode is "wb". This is the foundation for building any program that persists structured data across runs, from simple record managers to serialization libraries.

C program to write data to a binary file using fopen wb mode and fwrite, with step-by-step explanation.

📝 Problem Statement

Write a program in C to write data to a binary file.

⚙️ How the Program Works

The program follows the standard write lifecycle:

  1. Prepare the data — in this example, we build an array of Student structs, which is the most common use case for binary files.
  2. Open the file in write-binary mode with fopen("students.bin", "wb"). The "wb" mode creates the file or truncates it if it already exists.
  3. Check for NULL in case the file cannot be created.
  4. Write each record with fwrite(), passing the address of the record, its size, the count (usually 1), and the file pointer.
  5. Check fwrite's return value to detect a full disk or other write error.
  6. Close the file with fclose() to flush the buffer 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 students[3] = { { 101, "Alice", 87.5f }, { 102, "Bob", 91.0f }, { 103, "Carol", 78.5f } }; int i; size_t written; /* Open the binary file in write mode. "wb" creates the file or truncates it if it exists. */ fp = fopen("students.bin", "wb"); if (fp == NULL) { printf("Error: Could not create students.bin.\n"); return 1; } /* Write each record as raw bytes */ for (i = 0; i < 3; i++) { written = fwrite(&students[i], sizeof(struct Student), 1, fp); if (written != 1) { printf("Error: Failed to write record %d.\n", i + 1); fclose(fp); return 1; } } fclose(fp); printf("%d records written to students.bin successfully.\n", 3); return 0; }

🖥️ Sample Output

Console: 3 records written to students.bin successfully.

The file students.bin is now created on disk. Its exact byte content depends on the platform (padding, endianness, and struct alignment), but on a typical 64-bit Linux system each Student is 60 bytes (4 bytes for id, 50 for name, 4 for marks, plus padding). The total file size is therefore around 180 bytes. Opening the file in a text editor shows mostly unprintable characters — that's expected, because the data is stored in binary, not text.

To read these records back, see Assignment 8 (Read Binary Data from a Binary File).

🔍 Line-by-Line Explanation

Line / Code Explanation
struct Student { ... }; Defines the record layout that will be stored in the file. The reader must use the same struct.
students[3] = { ... }; Initializes an array of three records. In a real program you'd read these from user input.
fopen("students.bin", "wb") Opens for binary writing. Any existing content is truncated.
if (fp == NULL) Detects failure — for example, a full disk or a read-only directory.
fwrite(&students[i], sizeof(struct Student), 1, fp) Writes one full struct (its entire byte size) to the file. The first argument is the address, the second is the element size, the third is the count, and the fourth is the file pointer.
if (written != 1) Checks whether the write succeeded. fwrite returns the number of items successfully written; anything less than the requested count indicates an error.
fclose(fp) Flushes buffered bytes to disk and releases the file handle.
⚠️ Important: The "wb" mode truncates the file if it already exists. If you want to preserve existing records and add new ones, use "ab" (append binary) — that's the topic of Assignment 3.

📦 What Can You Write to a Binary File?

Anything that occupies a known number of contiguous bytes in memory can be written with fwrite. Some common examples:

Type Example call
Primitive variable fwrite(&num, sizeof(num), 1, fp);
Array of ints fwrite(arr, sizeof(int), n, fp);
Single struct fwrite(&s, sizeof(s), 1, fp);
Array of structs fwrite(arr, sizeof(struct Student), n, fp);
String buffer fwrite(buf, 1, strlen(buf), fp);

The two idioms are equivalent: fwrite(ptr, size, count, fp) and fwrite(ptr, 1, size * count, fp) write the same number of bytes. The first form is idiomatic when writing records; the second is convenient when writing raw byte buffers.

🌍 Portability Warning

Writing a raw struct to disk works perfectly when the file is read back by the same program on the same machine. It is not portable across platforms:

  • Padding: The compiler may insert unused bytes between struct fields. On a 64-bit machine, sizeof(struct Student) may be 60 bytes, while on an older 32-bit platform it could be 58.
  • Endianness: Intel and ARM chips store multi-byte integers in different byte order. A file written on x86 won't read correctly on big-endian hardware without conversion.
  • Pointer fields: A struct that contains a pointer stores the pointer's address, which is meaningless in another process.

For portable binary formats, write each field separately with explicit sizes (e.g., uint32_t) and document the endianness. For a learning exercise, writing the raw struct is fine.

🐛 Common Pitfalls

  • Forgetting the b in the mode: On Windows, text mode translates line endings and may mangle binary bytes. Always use "wb", not "w".
  • Missing fclose: Without it, buffered data never reaches the disk and the file may appear empty or truncated.
  • Ignoring fwrite's return value: A short write (a full disk, an interrupted process) is silently ignored if you don't check the count.
  • Writing a pointer field: Never store a struct that contains a pointer. The pointer's value is process-specific and useless on disk.
  • Truncating by accident: Using "wb" on a file you meant to append to destroys its content. Use "ab" when appending.

💡 Tips & Best Practices

  • Always use sizeof(struct YourStruct) rather than a hard-coded byte count — the struct layout can change between builds.
  • Store the record count at the start of the file if your reader needs to know how many records to expect.
  • Use a "magic number" or version byte at the start of the file so future readers can detect format changes.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch type mismatches.
  • Run xxd students.bin | head after writing to see the raw bytes — a great way to understand what fwrite actually does.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 3. Append Data to an Existing 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: -->> 6. Delete a Specific Line from a Text File   ||   Next Problem: -->> 8. Read Binary Data from a Binary File and Display It

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.