🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Embedded C File Seeking Lab
Free C programming course: update a record in place, then test yourself with a quiz and interview questions
This final lecture of the file position group in our free C programming course is a hands-on lab. You will patch one record of a binary file in place, which is how calibration values and settings are updated in embedded C programming. After the lab you get a quiz and a set of interview questions. If you are using this free embedded C course and free C tutorial to prepare for C programming for embedded systems roles, work through every question before you read the answers.
What You Will Learn in This Free C Programming Course
- How to update one record in a file without rewriting the rest
- Why you must reposition between a read and a write on an update stream
- How to verify the change by rewinding and dumping the file
- How to prepare for interview questions on fseek(), ftell() and rewind()
Prerequisites for the Free C Programming Course
Complete the previous lectures in this chapter and run the program that creates readings.dat. The lab depends on that file.
Lab Goal: Patch a Record in Place
Suppose a sensor was recalibrated and you must change one stored value. Rewriting the whole file is wasteful and risky. With fseek() you overwrite just that record. The “rb+” mode opens an existing file for reading and writing without truncating it.
Read-modify-write cycle on one record
Seek
Move to (n – 1) times record size
Read
fread the record into memory
Modify
Change the field in the structure
Seek again
Go back to the same offset
Write
fwrite the record, then flush
Why step 4 is required
After the read, the pointer sits at the start of the next record. A write now would overwrite the wrong record. Also, the C standard requires a positioning call such as fseek() or fflush() between a read and a write on an update stream. Skipping it is undefined behavior.
The Complete Lab Program
#include <stdio.h>
#include <stdlib.h>
struct reading {
int id;
char sensor[12];
float value;
};
int main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "usage: %s <record-number> <new-value>\n", argv[0]);
return 2;
}
long n = strtol(argv[1], NULL, 10);
float newval = strtof(argv[2], NULL);
FILE *fp = fopen("readings.dat", "rb+");
if (fp == NULL) { perror("fopen"); return 1; }
long offset = (n - 1) * (long)sizeof(struct reading);
if (n < 1 || fseek(fp, offset, SEEK_SET) != 0) {
fprintf(stderr, "cannot seek to record %ld\n", n);
fclose(fp);
return 1;
}
struct reading r;
if (fread(&r, sizeof r, 1, fp) != 1) {
fprintf(stderr, "record %ld does not exist\n", n);
fclose(fp);
return 1;
}
printf("before: %-10s %.1f\n", r.sensor, r.value);
r.value = newval;
/* switching from reading to writing needs a reposition */
if (fseek(fp, offset, SEEK_SET) != 0) { perror("fseek"); fclose(fp); return 1; }
if (fwrite(&r, sizeof r, 1, fp) != 1) { perror("fwrite"); fclose(fp); return 1; }
fflush(fp);
rewind(fp);
printf("file now:\n");
while (fread(&r, sizeof r, 1, fp) == 1)
printf(" %d %-10s %.1f\n", r.id, r.sensor, r.value);
fclose(fp);
return 0;
}
Build and run
gcc -std=c11 -Wall -Wextra -o patch_record patch_record.c
./make_readings
./patch_record 3 1009.4
Expected output
before: pressure 1012.8
file now:
1 temp 24.5
2 humidity 61.0
3 pressure 1009.4
4 light 340.0
5 co2 415.0
6 vibration 0.7
Only record 3 changed. The other five records are byte-for-byte the same. The lab uses every function from this chapter: fseek() to position, fread() and fwrite() for transfer, fflush() to push data out, rewind() to return to the start for the check.
Lab exercises
- Run the program with record 9 and observe the error message.
- Remove the second fseek() and run again. Check which record changed and explain why.
- Extend the program to print the file size before and after. It should not change.
- Change the name field instead of the value, and make sure the name stays terminated.
Common Mistakes in the Lab
Best Practices and Security
- Validate the record number against the file size before seeking.
- Flush or close the file promptly so the change reaches storage.
- For power-fail safety on embedded Linux use a temp file plus rename, or fsync().
Quiz: Test Your Understanding
Try each question first. Then open the answer.
Q1. The file is 26 bytes long. After fseek(fp, -3L, SEEK_END), what does ftell() return?
Show answer
23.
Q2. You have a file of 20 byte records. What is the offset of record 7 (counting from 1)?
Show answer
(7 – 1) times 20 = 120.
Q3. Which header defines SEEK_SET, SEEK_CUR and SEEK_END?
Show answer
stdio.h.
Q4. What does ftell() return when it fails?
Show answer
-1L, with errno set.
Q5. What is the return value of a successful fseek()?
Show answer
0.
Q6. Which open mode lets you read and overwrite an existing binary file without erasing it?
Show answer
“rb+” (also written “r+b”).
Q7. A program opens a file with “ab” and calls fseek(fp, 0L, SEEK_SET) before fwrite(). Where does the data go?
Show answer
To the end of the file. Append mode ignores the pointer for writes.
Q8. After reading the last record with fread(), feof() is true. What clears it besides closing the file?
Show answer
rewind(), a successful fseek(), or clearerr().
Q9. Is the expression fread(&r, sizeof r, 1, fp) == sizeof r a correct success test?
Show answer
No. fread() returns the number of items, which is 1 here, so compare with 1.
Q10. Why does reading then writing on an update stream need an fseek() or fflush() in between?
Show answer
The standard requires a positioning or flush call when switching direction, and the pointer has also moved past the record you read.
Interview Questions on fseek(), ftell() and rewind()
1. Explain the file position pointer in C.
It is a byte offset stored inside the FILE object. Reads and writes advance it. fseek(), ftell() and rewind() are the functions that change or report it.
2. How do you find the size of a file with only standard C?
Open it in binary mode, call fseek(fp, 0L, SEEK_END), then ftell(fp). Restore the position afterward if needed. The POSIX stat() call is an alternative.
3. What are the differences between rewind() and fseek(fp, 0L, SEEK_SET)?
Both move to byte 0 and clear end-of-file. rewind() also clears the error indicator and returns nothing, while fseek() returns a status you can check.
4. How would you read the 1000th record of a fixed-size record file?
Seek to 999 times the record size with SEEK_SET, then call fread() for one record and check that it returned 1.
5. What can go wrong when writing a struct directly to a file?
Padding bytes, integer byte order and floating point format differ between compilers and CPUs, so the file may not be portable. Also, uninitialized padding makes output nondeterministic unless the structure is cleared first.
6. What is the risk of using ftell() on a 32-bit system with a large file?
long may be 32 bits, which overflows above about 2 GiB. Use ftello() and fseeko() with off_t and enable large file support.
7. Why is while (!feof(fp)) a bad read loop?
feof() is true only after a read has hit the end. The loop runs once more and processes stale data. Test the return value of the read function instead.
8. What happens if you seek beyond the end of a file and then write?
On most systems the gap is filled with zero bytes, creating a sparse or zero-padded region. Behavior details depend on the platform.
9. How would you make an in-place update crash safe?
Write the new data to a temporary file, flush and sync it, then rename it over the original. Rename is atomic on POSIX file systems.
10. Why prefer binary mode for random access?
Text mode may translate line endings, so offsets would not match bytes, and the standard limits which offsets you may pass to fseek() on text streams.
Extra Challenges for Your Free C Programming Course
Finish the lab, then try these harder tasks. A good free C programming course should push you slightly beyond the lecture, and these do.
- Add a command that deletes a record by copying the last record over it and shrinking the file. On Linux, use
ftruncate()withfileno(). - Add a file header with a magic number, a version and a record count. Update the count after every append.
- Write a program that swaps two records in place using two seeks and two buffers.
- Build a tiny menu program that combines append, show, patch and count in one executable.
| Skill practiced | Where it applies |
|---|---|
| Header and version field | Firmware images, config files |
| Swap records | Sorting a file in place |
| Delete by overwrite | Compact logs on small storage |
| Menu program | Service and test tools |
Summary and Key Takeaways
- “rb+” plus fseek() updates one record without touching the others.
- Always reposition between a read and a write.
- Append mode cannot overwrite; it only adds at the end.
- Check every return value, and validate offsets before seeking.
Conclusion: Free C Programming Course Next Steps
You have finished the position-control topics of the files chapter in this free C programming course. You can now measure a file, read any record by number, add records, and patch them in place, which covers most of the file handling you will meet in embedded C programming. Keep practicing with your own record structures, and use the interview questions above as a checklist before attending interviews.
Frequently Asked Questions
How do I update one record in a binary file in C?
Open with “rb+”, fseek() to the record, read it, change it, fseek() back, fwrite() it, and flush.
Why did my update overwrite the wrong record?
You probably did not reposition after reading, so the write went to the next record.
Can I use “ab” for in-place updates?
No. Append mode always writes at the end.
Do I need fflush() after fwrite()?
Closing the file flushes it. Call fflush() when you need the data written earlier, or before reading back through the same stream.
Is this relevant to embedded systems without a file system?
The ideas carry over to flash storage and configuration blocks, where you address fixed-size slots by offset. The stdio functions themselves need a file system or a library port.
Where can I continue this free embedded C course?
Go to the next chapter after this one using the course index.
Great Work: Free C Programming Course
Review the quiz, redo the lab with your own record type, then move on to the next chapter.

2 Comments