🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Files Lab and Quiz
Build a binary sensor log with fwrite and fread, inspect it with a hex dump, then test yourself with a quiz and C file handling interview questions for embedded systems.
This final lecture of the opening section of Chapter 11 turns theory into practice. You will build a small sensor data logger in C that saves records in a binary file, reads them back, and also exports a readable text copy. It combines everything from the earlier lectures: streams, text versus binary, buffering, fopen modes and fclose. Then you will answer quiz questions and C file handling interview questions that employers commonly ask. This is the kind of hands-on exercise that makes our free C programming course useful for embedded C programming jobs, and a good checkpoint in any free embedded C course.
What You Will Learn
- How to store fixed-size records with
fwriteand load them withfread - How to guard against struct padding with
_Static_assert - How to check the return values that matter:
fopen,fwrite,fread,fclose - How to verify the file layout with
od - How to answer common C file handling interview questions
Prerequisites
Lectures 1 to 4 of Chapter 11, plus structures and fixed-width integer types. The fread and fwrite functions are covered in depth later in this free C tutorial; here you only need to know that they transfer a number of items of a given size.
Lab: Binary Sensor Log
The goal
A device samples temperature from one or two sensors. Each sample stores the time in milliseconds, the temperature in tenths of a degree, the sensor number and a flags byte. We save three samples to samples.bin, load them again, print them, and write the same data as comma separated text to samples.txt.
Why store temperature times ten?
Many microcontrollers have no floating point unit. Storing 24.5 degrees as the integer 245 keeps the record small, exact and fast, and the decimal point is added only when printing.
The program
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
struct sample {
uint32_t tick_ms;
int16_t temp_x10; /* temperature in tenths of a degree C */
uint8_t sensor_id;
uint8_t flags;
};
_Static_assert(sizeof(struct sample) == 8, "unexpected padding in struct sample");
static int save_log(const char *path, const struct sample *s, size_t n)
{
FILE *fp = fopen(path, "wb");
if (fp == NULL) {
perror(path);
return -1;
}
size_t done = fwrite(s, sizeof *s, n, fp);
if (fclose(fp) != 0 || done != n) {
fprintf(stderr, "short write to %s\n", path);
return -1;
}
return 0;
}
static int load_log(const char *path, struct sample *s, size_t max)
{
FILE *fp = fopen(path, "rb");
if (fp == NULL) {
perror(path);
return -1;
}
size_t n = fread(s, sizeof *s, max, fp);
fclose(fp);
return (int)n;
}
int main(void)
{
struct sample out[3] = {
{ 1000, 245, 1, 0 },
{ 2000, 251, 1, 0 },
{ 3000, 398, 2, 1 },
};
struct sample in[8];
if (save_log("samples.bin", out, 3) != 0)
return EXIT_FAILURE;
int n = load_log("samples.bin", in, 8);
if (n < 0)
return EXIT_FAILURE;
printf("records read back: %d (record size %zu bytes)\n", n, sizeof(struct sample));
for (int i = 0; i < n; i++)
printf("tick=%u ms sensor=%u temp=%d.%d C flags=%u\n",
(unsigned)in[i].tick_ms, (unsigned)in[i].sensor_id,
in[i].temp_x10 / 10, in[i].temp_x10 % 10, (unsigned)in[i].flags);
/* a human readable copy for debugging */
FILE *fp = fopen("samples.txt", "w");
if (fp == NULL) {
perror("samples.txt");
return EXIT_FAILURE;
}
for (int i = 0; i < n; i++)
fprintf(fp, "%u,%u,%d,%u\n", (unsigned)in[i].tick_ms,
(unsigned)in[i].sensor_id, in[i].temp_x10, (unsigned)in[i].flags);
fclose(fp);
return EXIT_SUCCESS;
}
Build, run and inspect
$ gcc -Wall -Wextra -std=c11 -o sensor_log sensor_log.c
$ ./sensor_log
records read back: 3 (record size 8 bytes)
tick=1000 ms sensor=1 temp=24.5 C flags=0
tick=2000 ms sensor=1 temp=25.1 C flags=0
tick=3000 ms sensor=2 temp=39.8 C flags=1
$ cat samples.txt
1000,1,245,0
2000,1,251,0
3000,2,398,1
$ od -An -tx1 samples.bin
e8 03 00 00 f5 00 01 00 d0 07 00 00 fb 00 01 00
b8 0b 00 00 8e 01 02 01
Decode the hex dump
The binary file is 24 bytes: three records of 8 bytes. Take the first record, e8 03 00 00 f5 00 01 00, and read it field by field on this little-endian machine.
| Bytes | Field | Little-endian value | Meaning |
|---|---|---|---|
e8 03 00 00 | tick_ms | 0x000003E8 = 1000 | 1000 ms |
f5 00 | temp_x10 | 0x00F5 = 245 | 24.5 degrees |
01 | sensor_id | 1 | Sensor 1 |
00 | flags | 0 | No flags |
Design decisions worth noticing
_Static_assertstops compilation if the compiler adds padding, so the file layout is the one you documented.- Fixed-width types make the field sizes the same on every platform.
fcloseis checked insave_log, because that call can reveal a failed final write.freadreturns how many complete records it got, so the caller prints only that many.- The text copy uses
fprintf; anyone can open it in a spreadsheet.
Challenges to try
- Change
save_logto open with"ab"so each run adds records instead of replacing the file, then read back and count them. - Create a boot counter: read an integer from
boot.cntwith"r"(use 0 if it does not exist), add one, and write it back with"w". - Use
"wx"to createsamples.binand print a clear message when it already exists. - Add a 4-byte magic number and a version byte at the start of the file and check them when loading.
Common Mistakes in This Lab
| Mistake | Symptom | Fix |
|---|---|---|
Opening the binary log with "w" instead of "wb" | Works on Linux, corrupts data on Windows | Always use the b flag |
Printing in[i] beyond n | Garbage values | Loop to the count returned by fread |
Skipping the sizeof check | Different record size on another compiler | Add _Static_assert |
Dividing a negative temp_x10 by ten and printing the remainder | Odd output such as -3.-5 | Print the sign separately and use the absolute value |
Chapter Summary and Key Takeaways
Revise this summary before you attempt the C file handling interview questions further down.
- Files give a program persistent memory; stdio streams are the portable way to use them.
- Text files store characters; binary files store bytes exactly as in memory and depend on type size and byte order.
- Data sits in a buffer until it is flushed or the file is closed.
"w"erases,"a"appends,"r"reads, the plus modes combine,bmarks binary andxprotects against overwriting.- Always check
fopenfor NULL, report errors withperror, and close every file you open.
Quiz Before the C File Handling Interview Questions
Pick an answer before you open the solution.
- What does
fopenreturn when it cannot open the file?- -1
- 0 as an int
- NULL
- EOF
Show answer
C. NULL, and
errnois set. - Which mode erases the contents of an existing file when it is opened?
"r""a""r+""w"
Show answer
D.
"w"truncates the file to zero length. - How many bytes does the text “1679” occupy in a text file (no newline)?
- 2
- 4
- 8
- It depends on the CPU
Show answer
B. One byte per digit character.
- What does
fflush(fp)do?- Deletes the file
- Sends buffered output to the operating system
- Closes the file
- Guarantees data is on the physical disk
Show answer
B. It hands data to the kernel; it does not guarantee physical storage.
- Which standard stream is unbuffered by default?
- stdin
- stdout
- stderr
- none of them
Show answer
C.
stderr. - What happens with
fopen("data.bin", "r+")if data.bin does not exist?- It is created
- It returns NULL
- It is created and truncated
- The program exits
Show answer
B.
"r+"requires an existing file. - Which mode always places new data at the end of the file?
"a""w""r+""rb"
Show answer
A. Append mode (and
"a+") writes at the end regardless of the position. - Why use
uint16_tinstead ofintin a binary file format?- It is faster to type
- Its size is fixed,
intis not - Only uint16_t can be written with fwrite
- It avoids endianness
Show answer
B.
intmay be 16 or 32 bits;uint16_tis always 16. Endianness still applies. - What is wrong with using a
FILE *afterfclose?- Nothing
- Undefined behaviour
- It reopens the file
- It only produces a warning
Show answer
B. The stream no longer exists.
- What effect does the
bin"rb"have on Linux?- It makes the file read-only
- It converts line endings
- None, but it keeps code portable
- It enables buffering
Show answer
C. POSIX systems ignore it, and other platforms rely on it.
Predict the Result: C File Handling Interview Questions Warm-Up
- A file contains
ABfollowed by a newline. You open it with"a"and writeCplus a newline. What is in the file?Show answer
Two lines:
ABandC. Append mode keeps the old data. - A 100-byte file is opened with
"w+". What is its size immediately afterfopensucceeds?Show answer
0 bytes. The write modes truncate on open.
- What is wrong with
fp = fopen("x.txt", 'r');?Show answer
The mode must be a string. A character constant is an integer, which does not match the pointer parameter and gives undefined behaviour at run time.
C File Handling Interview Questions
These C file handling interview questions run from basic to practical. Try to answer aloud before you open each one.
1. What is the difference between a text file and a binary file?
Text files hold characters and line endings and are human readable; binary files hold raw memory bytes. Binary is faster and smaller for numbers but depends on type sizes, padding and byte order, while text is portable.
2. Why must you check the return value of fopen?
It returns NULL on any failure: missing file, permission problem, full disk, too many open files. Using the NULL pointer afterwards crashes the program. Check it and report the reason with perror.
3. What is the difference between “w” and “a”?
"w" truncates an existing file or creates a new one; "a" keeps existing data and writes only at the end.
4. What is buffering and why is it used?
Output is collected in memory and written in larger blocks, which reduces the number of expensive system calls and device accesses. The trade-off is that data may be lost if the program dies before the buffer is flushed.
5. What is the difference between fflush and fsync?
fflush moves data from the stdio buffer to the kernel. fsync, a POSIX call, asks the kernel to write its cached data to the storage device. For power-loss safety you need both.
6. What happens to buffered data if the program crashes?
It is lost, because the stdio buffer lives in the process memory and is not flushed. Normal return from main and exit flush it; abort or a kill signal do not.
7. How are stdio functions different from open, read and write?
stdio is portable standard C with buffering and formatted I/O through FILE *. The others are POSIX system calls using integer file descriptors, with no buffering, giving precise control for device files and sockets.
8. How can you avoid overwriting an existing file by accident?
Open with "wx" (C11), or on POSIX use open with O_CREAT | O_EXCL. This makes the check and the creation a single atomic step.
9. Why is it risky to fwrite a struct to a file that other systems will read?
Padding, member sizes and byte order can differ by compiler and CPU. Use fixed-width types, check the size with _Static_assert, write fields in a defined byte order, or choose a text format.
10. How would you update a configuration file safely on an embedded Linux device?
Write the new content to a temporary file in the same directory, flush and fsync it, then call rename to replace the original. If power fails, you keep either the complete old file or the complete new one.
Frequently Asked Questions
Where can I practise C file handling interview questions?
Work through the interview section above, rebuild the sensor logger from memory, and then try the four challenges. This free C programming course adds more practice at the end of each chapter.
Where can I learn C file handling for free?
This free C programming course from EmbeddedPathashala covers file handling step by step with tested examples, quizzes and interview questions.
Is C file handling used in embedded systems?
Yes. Embedded Linux devices read configuration and write logs with stdio, and microcontrollers use the same ideas with SD cards and flash file systems such as FatFs.
Should I use fread and fwrite or fprintf for logs?
Use fprintf when people must read the log; use fwrite for compact, high-rate data that tools will decode.
How do I view a binary file?
Use od -An -tx1 file or hexdump -C file on Linux.
What should I study after this?
Reading and writing functions: fgetc, fputc, fgets, fread, fwrite, followed by file positioning with fseek and ftell.
Does this free embedded C course need special hardware?
No. A Linux PC with gcc is enough for every example in this chapter.
Ready for reading and writing functions?
Bookmark these C file handling interview questions, then continue the free C tutorial with character, string and block I/O on files, and file positioning.

2 Comments