🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Modify Records in C Files
Learn how to modify records in a binary file in C: find a record, step back with fseek, and overwrite it in place. Part of the free C programming course on EmbeddedPathashala, written for embedded C programming students.
To modify records in a binary file in C you read records one at a time until you find the one you want, change it in memory, jump the file position back by exactly one record, and write it over the old bytes. Nothing is copied and nothing is shifted. This lecture of our free C programming course builds that idea from scratch using a small sensor-node database, the kind of fixed-size record store you meet in embedded C programming when a device keeps calibration data or logs on an SD card or flash filesystem.
If you are following this free C tutorial in order, you already know fread(), fwrite(), fseek() and ftell(). Here we combine them into the first real file-update algorithm. It is also the first lecture of a five-part set that finishes with deleting, sorting and merging records, so the sample data file we create now is reused in every lecture that follows.
Topics and Keywords
What You Will Learn
- Why fixed-size records make in-place updates possible in a binary file.
- How to open a file in
rb+mode and why it differs fromwbandab. - How the file position moves during a read loop, and why a write needs one step back.
- The subtle bug hidden in
fseek(fp, -sizeof rec, SEEK_CUR)and how to avoid it. - The read-to-write switching rule of the C standard for update streams.
- How to test the program and read the expected output.
Prerequisites
- Structures and
typedef(Structure and Union chapter). - Binary file I/O with
fread()andfwrite()(earlier lectures of this chapter). - File position functions
fseek(),ftell()andrewind(). - A C compiler such as gcc on Linux, or any toolchain that supports C11.
Why Fixed-Size Records Make Updates Easy
A text file is a stream of characters with no fixed shape. If you change the number 9 to 10 inside a text file, the file becomes one byte longer and every byte after it has to move. That is why text files are copied, not patched. A binary file of structures behaves differently. If every record occupies exactly sizeof(node_t) bytes, then record number n always starts at byte n x sizeof(node_t). Replacing a record means overwriting that exact slice of bytes with another slice of the same size, so the rest of the file never notices.
| Property | Text file | Binary file of fixed-size records |
|---|---|---|
| Size of one item | Varies with content | Always sizeof(struct) |
| Jump to item n | Read and count lines | fseek to n x sizeof(struct) |
| Change one value | Usually rewrite the file | Overwrite one record in place |
| Human readable | Yes | No, needs a dump tool |
| Portable across CPUs | Yes | Not guaranteed (padding, endianness) |
The Sensor Node Record and the Data File
Instead of a student database we will use a record an embedded engineer would recognise: a monitored sensor node with a short name, a numeric id and the last temperature reading. Put the structure in a small header so every program in this chapter shares the same layout.
/* node.h */
#ifndef NODE_H
#define NODE_H
typedef struct {
char name[16];
int id;
float temp;
} node_t;
#endif
| Field | Type | Size | Meaning |
|---|---|---|---|
| name | char[16] | 16 bytes | Node label, NUL terminated |
| id | int | 4 bytes | Unique node number |
| temp | float | 4 bytes | Last temperature in degrees C |
| Total | 24 bytes | No padding on common 32 and 64-bit targets | |
Next, a tiny generator program that creates nodes.dat with five records. Notice that it writes the whole array with a single fwrite() call and checks the return value.
/* mkdata.c */
#include <stdio.h>
#include "node.h"
int main(void)
{
const node_t seed[] = {
{ "pump", 7, 48.5f },
{ "fan", 3, 36.2f },
{ "boiler", 12, 91.0f },
{ "valve", 5, 22.4f },
{ "fan", 9, 41.8f },
};
FILE *fp = fopen("nodes.dat", "wb");
if (fp == NULL) {
perror("nodes.dat");
return 1;
}
if (fwrite(seed, sizeof seed[0], 5, fp) != 5) {
perror("fwrite");
fclose(fp);
return 1;
}
fclose(fp);
printf("nodes.dat created: 5 records, %zu bytes each\n", sizeof(node_t));
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o mkdata mkdata.c
$ ./mkdata
nodes.dat created: 5 records, 24 bytes each
$ ls -l nodes.dat
-rw-r--r-- 1 root root 120 Oct 31 15:29 nodes.dat
Five records of 24 bytes give 120 bytes, which matches the listing. A quick size check like this is the cheapest way to confirm that your structure has no hidden padding.
How the File Position Moves While You Update
Every FILE stream owns a position indicator. A successful fread() of one record advances it by one record. That single fact causes the classic update bug: when your loop finds the matching record, the position is already past it, sitting at the start of the next record. If you call fwrite() right away, you destroy the neighbour instead of fixing the target. The cure is to step back one record first. The diagram shows the four moments that matter.
Writing the Program to Modify Records in a Binary File
The program takes a node id and a new temperature from the command line, so you can test it without typing into prompts. It opens the file in rb+, scans for the id, patches the temperature in a local copy, seeks back and writes.
/* modify.c */
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
int main(int argc, char *argv[])
{
FILE *fp;
node_t n;
int target;
float new_temp;
int found = 0;
if (argc != 3) {
fprintf(stderr, "usage: %s <id> <new_temp>\n", argv[0]);
return 2;
}
target = atoi(argv[1]);
new_temp = (float)atof(argv[2]);
fp = fopen("nodes.dat", "rb+");
if (fp == NULL) {
perror("nodes.dat");
return 1;
}
while (fread(&n, sizeof n, 1, fp) == 1) {
if (n.id == target) {
n.temp = new_temp;
if (fseek(fp, -(long)sizeof n, SEEK_CUR) != 0) {
perror("fseek");
break;
}
if (fwrite(&n, sizeof n, 1, fp) != 1) {
perror("fwrite");
break;
}
fflush(fp);
found = 1;
break;
}
}
fclose(fp);
if (found)
printf("node %d updated to %.1f\n", target, new_temp);
else
printf("node %d not found\n", target);
return found ? 0 : 1;
}
Reading the Code Line by Line
- rb+ opens an existing file for reading and writing without truncating it. The file must already exist; if it does not,
fopen()returns NULL. - fread() == 1 is the loop condition. It stops cleanly at end of file and also on a read error.
- n.temp = new_temp edits only the in-memory copy. The file is untouched until
fwrite(). - fseek(fp, -(long)sizeof n, SEEK_CUR) moves the position back by 24 bytes relative to where it is now.
- fwrite() replaces exactly 24 bytes, the old record.
- fflush() pushes the buffered bytes to the operating system before we close, which also satisfies the update-stream rule explained below.
- break ends the scan early. Ids are unique, so there is nothing more to find.
sizeof yields an unsigned type, so -sizeof n is a huge positive number, not minus 24. Converting to long first gives a real negative offset. This one cast is the difference between a working update and a seek to a wild position.Build, Run and Expected Output
$ ./mkdata
nodes.dat created: 5 records, 24 bytes each
$ gcc -std=c11 -Wall -Wextra -o modify modify.c
$ ./modify 3 40.0
node 3 updated to 40.0
$ ./modify 99 1.0
node 99 not found
$ echo $?
1
To see the file contents we use a small viewer that reads records back and prints them. It is the same loop you already know, with an index counter.
/* dump.c */
#include <stdio.h>
#include "node.h"
int main(int argc, char *argv[])
{
const char *path = (argc > 1) ? argv[1] : "nodes.dat";
FILE *fp = fopen(path, "rb");
node_t n;
int idx = 0;
if (fp == NULL) {
perror(path);
return 1;
}
printf("%-4s %-10s %-4s %s\n", "REC", "NAME", "ID", "TEMP");
while (fread(&n, sizeof n, 1, fp) == 1) {
printf("%-4d %-10s %-4d %.1f\n", idx++, n.name, n.id, n.temp);
}
fclose(fp);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o dump dump.c
$ ./dump
REC NAME ID TEMP
0 pump 7 48.5
1 fan 3 40.0
2 boiler 12 91.0
3 valve 5 22.4
4 fan 9 41.8
Only record 1 changed, from 36.2 to 40.0. Every other record is byte-for-byte identical, and the file size is still 120 bytes.
The Read and Write Switching Rule
The C standard says that on a stream opened for update, you may not follow an input operation directly with an output operation, or the reverse, unless a positioning call (fseek(), fsetpos(), rewind()) or an fflush() sits between them. Some libraries are forgiving and some silently misbehave, which makes this a portability trap. In our program the fseek() between fread() and fwrite() satisfies the rule naturally. If you ever skip the seek, for example when appending a record you just read, add an explicit fseek(fp, 0, SEEK_CUR).
Two Other Ways to Reach the Record
Remember the Offset Before Reading
Instead of stepping back with a relative seek, record the offset with ftell() before every read, and jump to it by absolute position when you find the match.
long pos;
for (;;) {
pos = ftell(fp);
if (fread(&n, sizeof n, 1, fp) != 1)
break;
if (n.id == target) {
n.temp = new_temp;
fseek(fp, pos, SEEK_SET);
fwrite(&n, sizeof n, 1, fp);
break;
}
}
Jump Straight to a Record Number
When the record number is known, no scan is needed. Record 4 starts at 4 * sizeof(node_t).
fseek(fp, 4L * (long)sizeof(node_t), SEEK_SET);
fread(&n, sizeof n, 1, fp);
| Technique | Needs a scan? | Best when |
|---|---|---|
| fseek relative, minus one record | Yes | You search by a field such as id |
| ftell then fseek absolute | Yes | You want the offset for later use |
| fseek to index times size | No | Record number is already known |
Real-World Use in Embedded Systems
Embedded Linux gateways, data loggers and bootloader tools often keep small tables on a filesystem: per-sensor calibration offsets, last-known thresholds, device registration entries. Rewriting a whole table because one gain value changed wastes time and, on flash storage, wears blocks. An in-place record update touches only the sectors that hold that record. Be aware that a flash translation layer may still rewrite a whole block underneath, so in-place updating reduces your own I/O but does not remove flash wear.
Common Mistakes and Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Next record gets overwritten | Forgot to seek back after the read | Add the relative fseek before fwrite |
| File becomes empty | Opened with “wb” or “w+b” | Use “rb+” |
| Record always written at end | Opened with “ab” or “ab+” | Append mode ignores seek for writes; use “rb+” |
| fseek jumps to a huge offset | Negated an unsigned sizeof | Cast to long first |
| fopen returns NULL | File does not exist yet | Create it first or fall back to “wb+” |
| Garbage after moving file to another board | Different padding or endianness | Define a fixed on-disk format |
Best Practices, Performance and Security
- Always use
sizeof(record), never a hard-coded 24, so the code survives a field change. - Check the return value of
fseek()andfwrite(). A full disk or a read-only mount fails quietly otherwise. - Stop scanning as soon as the target is found. For big files, keep an index in memory or use sorted records and a binary search.
- Validate command-line input.
atoi()returns 0 for junk;strtol()lets you detect it. - Treat file content as untrusted. If a file can be edited by others, force a NUL into
name[15]before printing it. - A single-record write is not atomic. If power can fail mid-write, write a copy and rename it, as shown in the next lecture.
Key Takeaways
- Fixed-size records let you overwrite one record without touching the others.
- After a read, the position is already past the record, so seek back by one record before writing.
- Write
-(long)sizeof rec, not-sizeof rec. - Use
rb+to update, and separate reads from writes with a positioning call. - Record offsets are simply index times record size.
Conclusion
You can now modify records in a binary file in C with confidence. The pattern is short: open with rb+, scan, edit a copy, seek back one record, write, flush. Every piece rests on the simple rule that a position indicator moves forward on each read. In the next lecture of this free embedded C course we handle the opposite problem. Overwriting works when the record keeps its size, but deleting a record shortens the file, and for that we need a temporary file and a rename.
Frequently Asked Questions
Can I change a record’s size when updating in place?
No. Overwriting only works when the new record has exactly the same size. Variable-size data needs a copy-and-rename approach or a format with length fields and free-space handling.
What is the difference between r+ and rb+?
On Linux there is none. On systems that translate line endings, the b marks binary mode and prevents corruption of record bytes. Always use rb+ for structure files.
Why is fflush needed after fwrite?
fwrite fills a buffer. fflush hands it to the operating system. It also acts as the positioning step required before switching an update stream from output to input.
Does fflush guarantee data is on the flash chip?
No. It only reaches the OS cache. Call fsync on the file descriptor (fileno(fp)) when you need durability across power loss.
How do I update many records fast?
Read a block of records into an array with one fread, edit the array, seek to the block start and write it back with one fwrite.
Why does my program overwrite the wrong record?
The usual cause is skipping the seek back after a successful read. The position is already past the record you meant to replace.
Continue the Free C Programming Course
Next we delete a record from a binary file using a temporary file, remove() and rename(). Practice this lecture by adding a command that updates the name field too.

1 Comment