C Binary Files

C Binary Files – fread() and fwrite()

Binary files are files that contain data in the same format used in memory—no text conversion involved. They are faster and more efficient when working with structured data like arrays or structs.

Unlike text files (which use functions like fprintf() and fscanf()), binary files use fwrite() and fread().

📥 fwrite() – Writing to Binary Files

fwrite() writes raw binary data from memory into a file.

fwrite(&data, size, count, file_pointer);

📤 fread() – Reading from Binary Files

fread() reads binary data from a file into memory.

fread(&data, size, count, file_pointer);

🧪 Example: Write & Read Struct in Binary File

#include <stdio.h>
#include <string.h>

struct Student {
    int id;
    char name[20];
};

int main() {
    struct Student s1 = {1, "Alex"};
    struct Student s2;

    FILE *fp = fopen("student.dat", "wb");

    if (fp == NULL) {
        printf("File creation failed!\n");
        return 1;
    }

    fwrite(&s1, sizeof(struct Student), 1, fp);
    fclose(fp);

    fp = fopen("student.dat", "rb");

    if (fp == NULL) {
        printf("File read error!\n");
        return 1;
    }

    fread(&s2, sizeof(struct Student), 1, fp);
    printf("ID: %d, Name: %s\n", s2.id, s2.name);

    fclose(fp);
    return 0;
}

Try It Now

📦 Why Use Binary Files?

  • Much faster for large datasets.
  • No need to convert numbers to text and back.
  • Great for saving arrays, structs, and complex data.

💡 Pro Tip

Always use sizeof() when reading/writing binary data to ensure compatibility across machines and compilers.

📚 Summary

  • fwrite() writes memory as raw bytes.
  • fread() reads those bytes back into memory.
  • Great for saving structured data like structs.

Ready to build your own database-style file system using C? Binary files are your best friend!