🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Binary Block I/O in C
Understand how fread() and fwrite() move raw bytes, why binary files are compact and fast, and when to use them.
This lecture of our free C tutorial introduces block input and output. Until now you stored data as text. In C programming for embedded systems you often log thousands of samples or keep a configuration blob in flash, and converting every number to text is wasteful. Block I/O lets you save a whole structure or array in one call, exactly as it lives in memory. You will compare text and binary bytes on disk, study the fread() and fwrite() prototypes, and learn the rules for item size and item count.
What You Will Learn
- How text files and binary files store the same value differently
- The item-size times item-count model behind fread() and fwrite()
- What size_t is and why you print it with %zu
- Which fopen() binary modes to use
- When block I/O is a good fit and when it is risky
Prerequisites
- fopen(), fclose() and file pointers
- Structures and arrays in C
- Basic hexadecimal notation
Text Files vs Binary Files on Disk
A text file stores characters. A binary file stores the raw bytes that sit in memory. The easiest way to feel the difference is to save one integer both ways.
#include <stdio.h>
int main(void)
{
int value = 123456;
FILE *t = fopen("value.txt", "w");
FILE *b = fopen("value.bin", "wb");
if (t == NULL || b == NULL) {
perror("fopen");
return 1;
}
fprintf(t, "%d", value);
fwrite(&value, sizeof value, 1, b);
fclose(t);
fclose(b);
printf("sizeof(int) on this machine = %zu\n", sizeof(int));
return 0;
}gcc -Wall -Wextra -std=c11 -o ep_text_vs_bin ep_text_vs_bin.c
./ep_text_vs_bin
ls -l value.txt value.binsizeof(int) on this machine = 4
-rw-r--r-- 1 user user 6 value.txt
-rw-r--r-- 1 user user 4 value.binNow look at the actual bytes with od:
od -An -tx1 value.txt
od -An -tx1 value.bin 31 32 33 34 35 36
40 e2 01 00The text file holds the six ASCII codes for the characters 1 to 6. The binary file holds four bytes: 123456 is 0x0001E240, and this machine stores the lowest byte first (little-endian), giving 40 e2 01 00.
The Block I/O Idea in C
Block I/O moves a number of equal-sized items in one call. You tell the library how big one item is and how many to move. Items can be single numbers, arrays or whole structures, which makes it ideal for fixed-size records such as sensor samples or configuration entries.
| Feature | Text I/O (fprintf, fscanf) | Block I/O (fwrite, fread) |
|---|---|---|
| Readable by people | Yes | No, needs a hex viewer |
| Size on disk | Grows with digit count | Fixed by the item size |
| Speed | Slower: converts numbers to text and back | Faster: straight byte copy |
| Portable across machines | Mostly | Only if layout is defined (see the lab lecture) |
| Best for | Reports, configs people edit | Logs, records, calibration data |
fread and fwrite Prototypes Explained
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fread ( void *ptr, size_t size, size_t nmemb, FILE *stream);| Parameter | Meaning |
|---|---|
| ptr | Address of the memory block. fwrite only reads from it, so it is const; fread writes into it |
| size | Bytes in one item |
| nmemb | How many items to transfer |
| stream | The FILE * returned by fopen() |
| Return value | Number of whole items transferred, not the number of bytes |
The total number of bytes moved is size * nmemb. The return value counts items, so a result smaller than nmemb means something went wrong or the file ended.
What is size_t in C?
size_t is the unsigned integer type the platform uses for sizes. Many older books define it as a plain unsigned int, but that is not guaranteed. Check on your own machine:
size_t=8 int=4 long=8That line is from a 64-bit Linux PC. On a typical 32-bit microcontroller size_t is usually 4 bytes. Print it with %zu, and let the compiler choose its size by writing sizeof instead of numbers.
Binary Mode and fopen Modes for Block I/O
| Mode | Action | Use it for |
|---|---|---|
| “wb” | Create or empty the file, then write | Saving a fresh binary file |
| “rb” | Open an existing file to read | Loading records |
| “ab” | Write at the end, keep old data | Appending log records |
| “r+b” | Read and write an existing file | Updating records in place |
| “w+b” | Create or empty, then read and write | Scratch files |
Warning: On Windows a file opened without b converts line endings and can silently corrupt your bytes. Always add b for block I/O.
When Block I/O Is the Right Tool
- Fixed-size records that are written and read by the same program build.
- Large arrays of samples where text conversion would waste time and space.
- Calibration or configuration blobs stored on flash or an SD card.
Avoid raw structure dumps when a file must be shared between different CPUs or compilers, because padding bytes, byte order and type sizes may differ. The final lecture of this group shows how to design a safe file layout.
Common Mistakes and Best Practices
| Mistake | Fix |
|---|---|
| Opening with “w” or “r” instead of “wb” or “rb” | Always use the b modes for block I/O |
| Typing numbers like 4 or 8 for item size | Use sizeof so the code survives type changes |
| Printing size_t with %d or %u | Use %zu |
| Ignoring the return value | Compare it with nmemb every time |
| Opening a binary file in a text editor and saving it | Use od or xxd to inspect and never save |
- Name binary files with a clear extension such as .bin or .dat.
- Write a small header with a marker and version number (see the lab lecture).
- Keep record structures small and use fixed-width types from stdint.h.
Summary and Key Takeaways
- Binary files store raw memory bytes, text files store characters.
- fread() and fwrite() transfer nmemb items of size bytes each and return the item count.
- size_t is a platform-specific unsigned type: print it with %zu.
- Always use the b in binary modes: wb, rb, ab, r+b.
- Raw structure dumps are best for same-machine data with a fixed layout.
Conclusion
Block I/O is the first step towards fast, compact storage in a free embedded C course project. You now know the model and the prototypes. Next we study fwrite() in detail, with five real calling patterns and a record-writing program.
Frequently Asked Questions
What is block I/O in C?
Block I/O means reading or writing a group of fixed-size items in one call using fread() and fwrite(). The bytes are copied between memory and the file exactly as they are, without any text conversion.
Is size_t the same as unsigned int?
Not necessarily. size_t is an unsigned type chosen by the platform to hold object sizes. On 64-bit Linux it is 8 bytes, while int stays at 4 bytes, so never assume they match. Print it with %zu.
Do I need the b in “rb” and “wb” on Linux?
Linux does not translate line endings, so it works without b, but Windows does translate them and corrupts binary data. Always include b so the same code is portable.
Can I open a binary file in a text editor?
You can, but you will see unreadable characters. Use a hex tool such as od -An -tx1 file or xxd to inspect the real bytes.
When should I choose text files over binary files?
Choose text when people need to read or edit the file, or when the data moves between different systems. Choose binary for compact, fast storage of fixed-size records on the same kind of machine.
Why is block I/O faster than many fprintf calls?
A single fwrite() copies a whole block with no number-to-text conversion and no parsing on the way back, so the CPU and the buffer do far less work.
Keep Learning Free Embedded C
Next up: fwrite() in depth with arrays, structures and partial writes.

2 Comments