How to Modify Records in C Files- Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

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.

24
bytes per record
rb+
update mode
1
fseek call that saves the next record

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

free c programming coursefree c tutorialembedded c programmingfree embedded c courserb+ modefseek SEEK_CURfixed-size records

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 from wb and ab.
  • 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() and fwrite() (earlier lectures of this chapter).
  • File position functions fseek(), ftell() and rewind().
  • 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.

PropertyText fileBinary file of fixed-size records
Size of one itemVaries with contentAlways sizeof(struct)
Jump to item nRead and count linesfseek to n x sizeof(struct)
Change one valueUsually rewrite the fileOverwrite one record in place
Human readableYesNo, needs a dump tool
Portable across CPUsYesNot 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
FieldTypeSizeMeaning
namechar[16]16 bytesNode label, NUL terminated
idint4 bytesUnique node number
tempfloat4 bytesLast temperature in degrees C
Total24 bytesNo 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.

Position indicator during an in-place update (target is Rec 1)
1. After fopen: position at start of file
position hereRec 0 pumpRec 1 fanRec 2 boilerRec 3 valveRec 4 fan
2. After fread matches Rec 1: position moved past it
Rec 0 pumpRec 1 fan (in memory)position hereRec 2 boilerRec 3 valveRec 4 fan
3. After fseek minus one record from current position
Rec 0 pumpposition hereRec 1 fan (old bytes)Rec 2 boilerRec 3 valveRec 4 fan
4. After fwrite of the edited copy
Rec 0 pumpRec 1 fan (new bytes)position hereRec 2 boilerRec 3 valveRec 4 fan

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.
Cast before you negate. 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);
TechniqueNeeds a scan?Best when
fseek relative, minus one recordYesYou search by a field such as id
ftell then fseek absoluteYesYou want the offset for later use
fseek to index times sizeNoRecord 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

SymptomLikely causeFix
Next record gets overwrittenForgot to seek back after the readAdd the relative fseek before fwrite
File becomes emptyOpened with “wb” or “w+b”Use “rb+”
Record always written at endOpened with “ab” or “ab+”Append mode ignores seek for writes; use “rb+”
fseek jumps to a huge offsetNegated an unsigned sizeofCast to long first
fopen returns NULLFile does not exist yetCreate it first or fall back to “wb+”
Garbage after moving file to another boardDifferent padding or endiannessDefine 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() and fwrite(). 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.

💬 Need help or career guidance? Ask us!Contact Us →

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2026 embeddedpathashala.com - WordPress Video Theme by WPEnjoy
×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →