🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Binary File Lab and Quiz
Build a safe binary config store, understand structure padding, then test yourself with a quiz and interview questions.
This closing lecture of the block I/O series in our free embedded C course puts everything together. You will build a binary configuration store for embedded C programming, see how structure padding changes file size, and check your knowledge with a quiz, programming challenges and interview questions. It is part of a free C programming course that treats files the way real firmware does: validated, versioned and carefully sized.
What You Will Learn
- How to design a binary file with a magic number, version and count
- How to write a loader that rejects damaged or foreign files
- How structure padding affects sizeof and file size
- A portability checklist for binary files
- Quiz and interview questions on fread, fwrite and the standard streams
Prerequisites
- The previous block I/O lectures (cp11_19 to cp11_21)
- fixed-width types from stdint.h
- Structures and sizeof
Lab: A Binary Config Store for Embedded C
Goal: save and reload a list of channel settings in a file. The file begins with a small header, so the loader can reject foreign or outdated files, followed by the entries.
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define CFG_MAGIC 0x45504346u /* "EPCF" marker */
#define CFG_VERSION 1u
struct cfg_header {
uint32_t magic;
uint16_t version;
uint16_t count;
};
struct cfg_entry {
uint16_t channel;
uint16_t period_ms;
uint32_t threshold;
};
static int cfg_save(const char *path, const struct cfg_entry *e, uint16_t n)
{
struct cfg_header h = { CFG_MAGIC, CFG_VERSION, n };
FILE *fp = fopen(path, "wb");
if (fp == NULL)
return -1;
if (fwrite(&h, sizeof h, 1, fp) != 1 ||
fwrite(e, sizeof *e, n, fp) != n) {
fclose(fp);
return -1;
}
return fclose(fp) == 0 ? 0 : -1;
}
static int cfg_load(const char *path, struct cfg_entry *e, uint16_t max)
{
struct cfg_header h;
FILE *fp = fopen(path, "rb");
if (fp == NULL)
return -1;
if (fread(&h, sizeof h, 1, fp) != 1 || h.magic != CFG_MAGIC ||
h.version != CFG_VERSION || h.count > max ||
fread(e, sizeof *e, h.count, fp) != h.count) {
fclose(fp);
return -2;
}
fclose(fp);
return h.count;
}
int main(void)
{
struct cfg_entry out[3] = { {0, 100, 512}, {1, 250, 900}, {2, 500, 1500} };
struct cfg_entry in[8];
int n, i;
if (cfg_save("cfg.bin", out, 3) != 0) {
perror("save");
return 1;
}
printf("header %zu bytes + 3 x %zu bytes entries\n",
sizeof(struct cfg_header), sizeof(struct cfg_entry));
n = cfg_load("cfg.bin", in, 8);
if (n < 0) {
printf("load failed (%d)\n", n);
return 1;
}
for (i = 0; i < n; i++)
printf("ch%u every %u ms, threshold %u\n",
(unsigned)in[i].channel, (unsigned)in[i].period_ms,
(unsigned)in[i].threshold);
/* corrupt the magic byte and try again */
{
FILE *fp = fopen("cfg.bin", "r+b");
if (fp) { fputc(0x00, fp); fclose(fp); }
}
printf("after corruption: load returns %d\n", cfg_load("cfg.bin", in, 8));
return 0;
}gcc -Wall -Wextra -std=c11 -o ep_cfg_store ep_cfg_store.c
./ep_cfg_store
ls -l cfg.binheader 8 bytes + 3 x 8 bytes entries
ch0 every 100 ms, threshold 512
ch1 every 250 ms, threshold 900
ch2 every 500 ms, threshold 1500
after corruption: load returns -2
-rw-r--r-- 1 user user 32 cfg.binThe program wrote 8 + 24 = 32 bytes, loaded them back, then overwrote the first byte of the file. The loader noticed the magic number was wrong and refused the file instead of using bad settings.
How the Loader Protects You
- Read the header and check that fread() returned 1.
- Compare the magic number and the version.
- Reject a count larger than the destination array, which stops buffer overflows.
- Read exactly count entries and check the returned count.
- Close the file on every path, including errors.
Structure Padding and File Size
Padding is the hidden reason raw structure dumps are risky. Here two structures hold the same three values in a different order.
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
struct loose { uint8_t mode; uint32_t period; uint8_t flags; };
struct tidy { uint32_t period; uint8_t mode; uint8_t flags; };
int main(void)
{
printf("loose : size=%zu offsets mode=%zu period=%zu flags=%zu\n",
sizeof(struct loose), offsetof(struct loose, mode),
offsetof(struct loose, period), offsetof(struct loose, flags));
printf("tidy : size=%zu offsets period=%zu mode=%zu flags=%zu\n",
sizeof(struct tidy), offsetof(struct tidy, period),
offsetof(struct tidy, mode), offsetof(struct tidy, flags));
return 0;
}gcc -Wall -Wextra -std=c11 -o ep_pad ep_pad.c
./ep_padloose : size=12 offsets mode=0 period=4 flags=8
tidy : size=8 offsets period=0 mode=4 flags=5| Layout | Size | Wasted bytes |
|---|---|---|
| loose: 1-byte, 4-byte, 1-byte | 12 | 6 |
| tidy: 4-byte, 1-byte, 1-byte | 8 | 2 (tail padding) |
Portability Checklist for Binary Files
| Risk | Example | Safer approach |
|---|---|---|
| Type sizes differ | int is 2 bytes on one MCU, 4 on another | Use uint16_t, uint32_t |
| Byte order differs | Little-endian PC, big-endian target | Define the order and write bytes explicitly |
| Padding differs | Different compilers align differently | Order fields large to small, add a version |
| Pointers inside records | Addresses change each run | Store data or indexes |
| Format changes | New field added later | Keep a version number in the header |
Quiz: Check Your Binary File Knowledge
Q1. What does fwrite() return?
- A. Number of bytes written
- B. Number of items written
- C. 1 for success and 0 for failure
- D. The file pointer
Answer: B
Q2. With int arr[10] and 4-byte int, what does fwrite(arr, sizeof(int), 5, fp) write?
- A. 5 bytes
- B. 10 bytes
- C. 20 bytes
- D. 40 bytes
Answer: C
Q3. Which mode opens an existing binary file for reading?
- A. “r”
- B. “rb”
- C. “wb”
- D. “ab”
Answer: B
Q4. Why use sizeof instead of the typed number 4?
- A. It runs faster
- B. It follows type changes and other targets
- C. The compiler requires it
- D. It avoids buffering
Answer: B
Q5. fread() was asked for 5 records and returned 2. What can you conclude?
- A. Everything worked
- B. The file ended or an error occurred
- C. The buffer is too large
- D. The mode was wrong
Answer: B
Q6. What is the size of a file after fwrite() stores 3 records of 8 bytes?
- A. 3 bytes
- B. 8 bytes
- C. 11 bytes
- D. 24 bytes
Answer: D
Q7. Why is while(!feof(fp)) a poor read loop?
- A. feof() is not a standard function
- B. The flag is set only after a read fails, so one extra pass runs
- C. It reads too fast
- D. It always returns 1
Answer: B
Q8. struct { uint8_t a; uint32_t b; } is most likely how many bytes on a typical 32-bit or 64-bit compiler?
- A. 5
- B. 6
- C. 8
- D. 4
Answer: C
Q9. fscanf() could not match the text. What does it return?
- A. EOF always
- B. The number of items converted so far, possibly 0
- C. -1 always
- D. The length of the text
Answer: B
Q10. Which call is the same as printf(“ok\n”)?
- A. fprintf(stdin, “ok\n”)
- B. fprintf(stderr, “ok\n”)
- C. fprintf(stdout, “ok\n”)
- D. fscanf(stdout, “ok\n”)
Answer: C
Programming Challenges
- Extend the config store so each entry also holds a 1-byte enable flag. Predict the new sizeof before compiling, then confirm it with the program.
- Write a program that reads cut.bin from the fread lecture and prints “damaged file” when the size is not a multiple of the record size.
- Change print_report() so it also takes a column width, and test it with stdout and a file.
- Add a checksum field to the header and reject files whose checksum does not match.
C File I/O Interview Questions
Q1. What is the difference between text I/O and block I/O?
Text I/O converts values to and from characters with functions like fprintf and fscanf. Block I/O copies raw memory bytes with fwrite and fread, which is smaller and faster but not human readable and sensitive to layout.
Q2. Explain the arguments of fread().
ptr is the destination buffer, size is the bytes per item, nmemb is the number of items, and stream is the file. It returns the number of complete items read.
Q3. How do you tell end of file from an error after a short fread()?
Call feof() and ferror(). feof() non-zero means the end was reached, ferror() non-zero means a read error.
Q4. Why can writing a structure to a file and reading it on another machine fail?
The two builds may differ in type sizes, byte order or padding, so the same bytes mean different values.
Q5. What is structure padding and how do you reduce it?
The compiler inserts unused bytes so fields are aligned. Order fields from largest to smallest to reduce it.
Q6. Why does a good file format begin with a magic number and version?
It lets a loader reject wrong files and handle older layouts safely instead of misinterpreting data.
Q7. Why is printf() equal to fprintf(stdout, …)?
stdout is the stream printf writes to, so naming it explicitly changes nothing. The same holds for scanf and stdin.
Q8. How would you safely load a record count from a file?
Validate it against the capacity of the destination array before using it as a loop bound, then check the number of items fread() returns.
Q9. Why check the return value of fclose()?
Buffered data may be flushed during fclose(), so a full disk or flash error can appear only there.
Q10. When would you choose text files over binary files in an embedded project?
When people must read or edit the data, when different tools will parse it, or when the format must be portable across architectures.
Common Mistakes Recap and Best Practices
- Share one header between the writer and the reader.
- Use fixed-width integer types for anything stored in a file.
- Validate magic, version and counts before trusting file contents.
- Check every fread(), fwrite() and fclose() result.
- Keep a text format when portability matters more than size.
Summary and Key Takeaways
- A header with magic number and version protects against bad files.
- Always validate counts from a file before using them.
- Padding makes sizeof larger than the sum of fields, and reordering fields can shrink it.
- Raw structure dumps are portable only when type sizes, byte order and padding match.
- Check the results of fread(), fwrite() and fclose() every time.
Conclusion
You now know how to store and reload blocks of data in C and how to keep the file trustworthy. Random access with fseek() comes next in this free C programming course, letting you jump to any record by its number.
Frequently Asked Questions
Why do structures have padding bytes?
CPUs read data fastest when each field sits at an address that is a multiple of its size, so the compiler inserts unused bytes to align fields. These bytes are part of the structure and get written by fwrite().
How can I reduce padding?
Order fields from largest to smallest, as shown in the lab. Reordering removed 4 bytes from a 12-byte structure with no loss of data.
Is it safe to copy a binary file to another computer?
Only if both machines use the same byte order, type sizes and structure layout. Otherwise define the file format field by field and write each value with a fixed width and byte order.
Why store a magic number and version in a file header?
The magic number rejects files that are not yours, and the version lets newer software recognise an older layout and convert it instead of misreading it.
Should I use packed structures to remove padding?
Packing is a compiler extension and can cause slow or faulty unaligned access on some CPUs. Reordering fields or writing each field separately is safer.
Where can I practise these questions?
Work through the quiz and the interview section below, run every program yourself, and change the record layout to see how sizes and bytes change.
Finish Strong with Free C Tutorials
Next up: random access with fseek(), ftell() and rewind().

1 Comment