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.
📝 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:
- Define a struct that represents the type of record stored in the file.
- Prompt for the new record and fill the struct fields.
- Open the file with
fopen("records.bin", "ab"). The"ab"mode opens for appending in binary — creating the file if it doesn't exist. - Check for
NULLin case the file cannot be opened. - Write with
fwrite()to append the struct's bytes to the end of the file. - 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:
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:
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) |
"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
bin the mode: On Windows, text mode translates\nandEOFcharacters. Binary data must be read and written in binary mode or the bytes will be corrupted. - Forgetting to check
fopen: An uncheckedNULLpointer will crash the program on the firstfwrite. - 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
intandfloatmay differ. For cross-platform files, serialize fields one by one withfwriteon each field instead of dumping the whole struct. - Compile with
gcc -Wall -Wextra -std=c11 -gto catch type and size warnings.