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.
📝 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:
- Prepare the data — in this example, we build an array of
Studentstructs, which is the most common use case for binary files. - 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. - Check for
NULLin case the file cannot be created. - Write each record with
fwrite(), passing the address of the record, its size, the count (usually 1), and the file pointer. - Check
fwrite's return value to detect a full disk or other write error. - 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
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. |
"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
bin 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 -gto catch type mismatches. - Run
xxd students.bin | headafter writing to see the raw bytes — a great way to understand whatfwriteactually does.