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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

File I/O – Binary Files | C Programming Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 43 of 50

·c

File I/O – Binary Files

10 mins

Course progress86%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • `wb` opens a file for **binary write**, `rb` for binary read.
  • Binary I/O is fast and preserves exact memory layout (be aware of endianness).
  • `fwrite`/`fread` return the number of elements successfully processed.
  • Use `ftell`/`fseek` for random access within the file.

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;
}
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from C Programming FundamentalsBrowse activities
Previous lessonSignal Handling (`signal.h`)Continue to lesson 44Error Handling – `errno` & `perror`Back to C Programming Fundamentals curriculum