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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Workshop: A Text File Processing Pipeline →← Random Access File Operations in CNext lesson: Workshop: A Text File Processing Pipeline →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What do fread and fwrite return in C?
Why can't fscanf read a file written with fwrite?
What is little-endian byte order?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →