0
0
CHow-ToBeginner · 3 min read

How to Write Binary File in C: Simple Guide with Example

To write a binary file in C, use fopen with mode "wb" to open the file for writing in binary mode, then use fwrite to write data, and finally close the file with fclose. This ensures data is saved exactly as bytes without text conversion.
📐

Syntax

Here is the basic syntax to write binary data to a file in C:

  • FILE *fopen(const char *filename, const char *mode); opens the file. Use "wb" mode to write binary.
  • size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream); writes count items of size bytes from ptr to the file.
  • int fclose(FILE *stream); closes the file.

This combination writes raw bytes to the file without any formatting.

c
FILE *file = fopen("filename.bin", "wb");
if (file != NULL) {
    fwrite(data_pointer, size_of_element, number_of_elements, file);
    fclose(file);
}
💻

Example

This example writes an array of integers to a binary file named numbers.bin. It shows how to open the file, write the data, and close the file safely.

c
#include <stdio.h>

int main() {
    FILE *file = fopen("numbers.bin", "wb");
    if (file == NULL) {
        perror("Failed to open file");
        return 1;
    }

    int numbers[] = {10, 20, 30, 40, 50};
    size_t count = sizeof(numbers) / sizeof(numbers[0]);

    size_t written = fwrite(numbers, sizeof(int), count, file);
    if (written != count) {
        perror("Failed to write all data");
        fclose(file);
        return 1;
    }

    fclose(file);
    printf("Successfully wrote %zu integers to numbers.bin\n", written);
    return 0;
}
Output
Successfully wrote 5 integers to numbers.bin
⚠️

Common Pitfalls

  • Not opening the file in binary mode ("wb") can cause data corruption on some systems.
  • Forgetting to check if fopen returns NULL leads to crashes.
  • Writing fewer bytes than expected if fwrite return value is ignored.
  • Not closing the file with fclose can cause data loss.

Always check return values and open files in binary mode when writing binary data.

c
#include <stdio.h>

int main() {
    // Wrong: opening file in text mode
    FILE *file = fopen("data.bin", "w"); // Should be "wb"
    if (file == NULL) return 1;

    int value = 12345;
    // Wrong: ignoring fwrite return value
    fwrite(&value, sizeof(int), 1, file);

    // Correct: open in binary mode and check fwrite
    fclose(file);
    file = fopen("data.bin", "wb");
    if (file == NULL) return 1;
    if (fwrite(&value, sizeof(int), 1, file) != 1) {
        perror("Write error");
    }
    fclose(file);
    return 0;
}
📊

Quick Reference

Remember these key points when writing binary files in C:

  • Use "wb" mode in fopen to write binary files.
  • Use fwrite to write raw bytes from memory to the file.
  • Always check if fopen and fwrite succeed.
  • Close files with fclose to flush buffers and release resources.

Key Takeaways

Always open files with "wb" mode to write binary data correctly.
Use fwrite to write raw bytes and check its return value to ensure all data is written.
Check if fopen returns NULL to handle file opening errors gracefully.
Close files with fclose to save data and free resources.
Avoid mixing text and binary modes to prevent data corruption.