Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 43 of 50 · c

File I/O – Binary Files

Duration: 10 mins

Binary files store raw bytes without newline translation.

FILE *fp = fopen("data.bin", "wb");
int vals[5] = {10,20,30,40,50};
fwrite(vals, sizeof vals, 1, fp);
fclose(fp);

Reading:

FILE *fp = fopen("data.bin", "rb");
int vals[5];
fread(vals, sizeof vals, 1, fp);

Always check the return of fwrite/fread for the number of items written/read.


📚 Example: Storing a Struct to Disk

#include <stdio.h>
#include <stdint.h>

struct Record {
    uint32_t id;
    double   value;
    char     name[16];
};

int main(void) {
    struct Record r = { 42, 3.1415, "sample" };
    FILE *f = fopen("record.bin", "wb");
    if (!f) return 1;
    fwrite(&r, sizeof r, 1, f);
    fclose(f);
    return 0;
}
Previous: Signal Handling (`signal.h`)Next: Error Handling – `errno` & `perror`