Binary File I/O: fread() and fwrite() | Programming in C

UPI Study › Courses › Programming in C › Free lessons › Lesson 9.9 Free with a free account

Binary File I/O: fread() and fwrite()

Programming in C · Chapter 9: String Manipulation via Pointers, File Streams, and File HandlingSection 9.9 · lesson 62 of 786 min · free with a free account

← Random Access File Operations in CNext lesson: Workshop: A Text File Processing Pipeline →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

Writing and reading raw bytes with fwrite and fread.

  • Compare how a text file and a binary file store the same int
  • Use fwrite and fread with wb and rb modes to move whole blocks of data
  • Check the item count fread returns to detect short reads and the end of a file
  • Explain byte order and why binary files may not move safely between machines

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (888 words). Read along, or search it.

Opening Question

Storing the Number Itself

Write the number one thousand into a text file, and you store four characters: a one, and three zeros. Each one is a little code, and reading it back means turning those codes into a number again. What if the file simply kept the number itself, exactly as the computer holds it? That's a binary file. And it has a catch, which a real byte dump will show.

Text Versus Binary

Digit Codes Versus Raw Bytes

Everything in a file is bytes. A text file uses a text encoding: each character gets a number code. fprintf turns your int into digit characters first. A binary file skips that step, so it's faster. It stores the bytes of the value, exactly as they sit in memory. That's what fwrite does. This program writes the same int, 1000, both ways. Build it, run it, and dump each file's bytes with xxd. xxd prints bytes in hexadecimal, base 16, the way programmers usually write bytes. The digit 1 is code 49, which is 31 in hex. So the text file holds the codes of four digits. The binary file holds e8, 03, 00, 00: the number's own four bytes. Both files are four bytes this time, but that's luck. Text for seven takes one byte, and for a million, seven. An int in a binary file always takes sizeof(int) bytes, 4 on this Mac. Every item the same size makes jumping to the nth item easy.

Core Functions

Writing and Reading Whole Blocks

Open binary files with "wb" to write, or "rb" to read. The b means binary. On Mac and Linux it changes nothing, but elsewhere it matters, so always include it. fwrite takes four things: where the bytes are, the size of one item, how many items, and the stream. fread is the same, with the bytes going the other way. For one int, you pass its address. For an array, the name already is the address of its first item, so one call moves all five scores. Both return how many items they handled. Not bytes: items. Build and run it. 5 stored, 5 loaded, all correct. And seeking to 2 times sizeof(int) finds the third score, 480. Dump the file. Exactly 20 bytes, four per score, with no spaces and no newlines. The third score starts at byte 8.

Quick Check

Two Small Ints Take Eight Bytes

Quick check. This program writes two small ints, seven and twenty-five, with one fwrite call, on this Mac. How many bytes does pair.bin hold? Pause and predict. 8 bytes. Two items of sizeof(int), and an int is 4 bytes here, however small its value. Three would be the text digits, seven, two, five. Binary doesn't store digits: it stores each whole int.

Short Reads

Always Use the Returned Count

Always check that count. If it's smaller than you asked for, something went wrong: the file ended early, or the disk was full. Here the file holds three ints, but the program asks fread for five. Run it. fread returned three, and only the first three boxes of buffer were filled. The loop uses got, not five. A program that ignored the count would treat two empty boxes as scores.

Quick Check

Reading Two Ints at a Time

Quick check. three.bin is the 12-byte file from that last run: three ints. This program reads it two ints at a time. It calls fread three times, and prints the three counts. What will it print? Pause and predict. It prints 2 1 0. The first call gets two whole ints. Only one is left, so the second call returns one: a short read. The third call finds nothing at all, and returns zero. That's how a loop can tell the file is done. And the counts are items, never bytes. Eight, four, zero would be bytes.

Common Mistake

Text Tools Cannot Read Raw Bytes

Another trap: reading a binary file with text tools. fscanf and fgets expect characters and digits, but fwrite stored raw bytes. This program writes 410 with fwrite, then tries to read it back with fscanf and %d. Run it. Zero items matched, and value kept its marker, minus one. The first byte isn't a digit at all. Whatever wrote the file, read it with the matching partner: fwrite with fread, and fprintf with fscanf.

Byte Order

Little-Endian and Big-Endian Machines

Now the catch. A number bigger than two fifty-five needs several bytes, and there are two sensible orders for them. In hex, one thousand is three e8. With leading zeros, that's 00 00 03 e8, biggest piece first. But the dump showed e8 03 00 00. This Mac stores the smallest piece first. That's called little-endian. Computers that store the biggest piece first are big-endian. Neither is wrong. The names come from Gulliver's Travels, where two kingdoms fight over which end of an egg to crack. Priya once mailed Sam a score file made with fwrite, and on his machine every score came out wrong. She sent a text file instead, and it worked at once. Two machines can differ in byte order, and in the size of an int. So files that must travel are safer as text. Files your own program reads back are great as binary.

Key Takeaways

Raw Bytes, Item Counts, and Portability

To recap. A text file stores the codes of digits. A binary file stores a value's own bytes, each int the same size. Use "wb" and "rb", and move whole blocks with fwrite and fread. Both return a count of items. Check it, and use it. And byte order and int size vary between machines, so binary files may not travel.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Binary File I/O: fread() and fwrite()

What is the difference between a text file and a binary file in C?
A text file stores character codes, so fprintf turns the int 1000 into the codes for the digits 1, 0, 0, and 0. A binary file stores the value's own bytes exactly as they sit in memory, which is what fwrite writes. Every int then takes sizeof(int) bytes, often 4, whatever its value, so each item has the same size and the nth item is easy to find.
What do fread and fwrite return in C?
Both return the number of items they handled, not the number of bytes. If you ask fread for 5 ints and the file holds only 3, it returns 3 and fills only the first three elements. A result smaller than requested means the file ended early or an error occurred, so a loop should use the returned count rather than the number it asked for.
Why can't fscanf read a file written with fwrite?
fscanf and fgets expect characters, but fwrite stores raw bytes, so the first byte is usually not a digit at all. Writing 410 with fwrite and reading it back with fscanf and %d matches zero items and leaves the variable unchanged. Use matching pairs: read fwrite output with fread, and read fprintf output with fscanf.
What is little-endian byte order?
Little-endian means a machine stores the least significant byte of a number first. The int 1000 is 0x000003E8, so a little-endian machine writes the bytes e8 03 00 00, while a big-endian machine writes 00 00 03 e8. Because byte order and int size can differ between machines, a binary file may read wrongly elsewhere, and text is safer for data that must travel.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →