What are Random Access File Records- C Programming For Beginners

🚀 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 →

PREV_LEC | NEXT_LEC

Random Access File Records

Free C programming course: read the nth record of a binary file with fseek() and fread()

Reading the 500th record of a file without reading the first 499 is called random access. In this lecture of our free C programming course you will build two programs: one writes a binary file of fixed-size records, the other reads any record by its number. This pattern is everywhere in embedded C programming, from sensor logs to calibration tables, and it is a favorite exercise in any free embedded C course.

Treat this as a practical free C tutorial for C programming for embedded systems. The code is original and was compiled and run before being written here.

What You Will Learn in This Free C Programming Course

  • Why fixed-size records make the offset formula simple
  • The formula for the byte offset of record n
  • How to write a record file with fwrite()
  • How to read one record by number with fseek() and fread()
  • How to validate the record number using the file size

Prerequisites for the Free C Programming Course

You need the previous two lectures on the file position pointer and fseek(), plus structures and sizeof from earlier chapters of this free C programming course.

The Offset Formula for Random Access Records

If every record occupies exactly sizeof(struct reading) bytes, then record number n (counting from 1) begins at

offset = (n - 1) * sizeof(struct reading)

Records are numbered from 1 for humans, but offsets start at 0, so the first record sits at offset 0. We will use a small structure for a sensor reading.

struct reading {
    int   id;
    char  sensor[12];
    float value;
};

File layout: six records of 20 bytes each

RecordSensorStarts at byteEnds at byte
1temp019
2humidity2039
3pressure4059
4light6079
5co28099
6vibration100119

Reading record n without reading the others

1

Compute

offset = (n – 1) times record size

2

Seek

fseek(fp, offset, SEEK_SET)

3

Read

fread(&r, sizeof r, 1, fp)

Step 1: Create the Binary Record File

#include <stdio.h>
#include <string.h>

struct reading {
    int   id;
    char  sensor[12];
    float value;
};

int main(void)
{
    static const struct { const char *name; float value; } seed[] = {
        { "temp",      24.5f  },
        { "humidity",  61.0f  },
        { "pressure",  1012.8f },
        { "light",     340.0f },
        { "co2",       415.0f },
        { "vibration", 0.7f   },
    };
    const size_t count = sizeof seed / sizeof seed[0];

    FILE *fp = fopen("readings.dat", "wb");
    if (fp == NULL) { perror("fopen"); return 1; }

    for (size_t i = 0; i < count; i++) {
        struct reading r;
        memset(&r, 0, sizeof r);
        r.id = (int)(i + 1);
        strncpy(r.sensor, seed[i].name, sizeof r.sensor - 1);
        r.value = seed[i].value;
        if (fwrite(&r, sizeof r, 1, fp) != 1) {
            perror("fwrite");
            fclose(fp);
            return 1;
        }
    }
    fclose(fp);

    printf("sizeof(struct reading) = %zu bytes\n", sizeof(struct reading));
    printf("wrote %zu records\n", count);
    return 0;
}

Two details matter here. First, memset() clears the whole structure, including any padding bytes and unused characters of the name, so the file contents are predictable. Second, strncpy() with sizeof r.sensor - 1 keeps the last byte zero, so the name is always a valid string.

gcc -std=c11 -Wall -Wextra -o make_readings make_readings.c
./make_readings
sizeof(struct reading) = 20 bytes
wrote 6 records

Step 2: Read the Nth Record with fseek()

The reader takes the record number from the command line. It first learns the file size with fseek(fp, 0L, SEEK_END) followed by ftell(), divides by the record size to get the record count, and refuses numbers outside that range. Only then does it seek and read.

#include <stdio.h>
#include <stdlib.h>

struct reading {
    int   id;
    char  sensor[12];
    float value;
};

int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s <record-number>\n", argv[0]);
        return 2;
    }
    long n = strtol(argv[1], NULL, 10);

    FILE *fp = fopen("readings.dat", "rb");
    if (fp == NULL) { perror("fopen"); return 1; }

    if (fseek(fp, 0L, SEEK_END) != 0) { perror("fseek"); fclose(fp); return 1; }
    long size  = ftell(fp);
    long total = size / (long)sizeof(struct reading);

    if (n < 1 || n > total) {
        fprintf(stderr, "record %ld out of range (file has %ld)\n", n, total);
        fclose(fp);
        return 1;
    }

    long offset = (n - 1) * (long)sizeof(struct reading);
    if (fseek(fp, offset, SEEK_SET) != 0) { perror("fseek"); fclose(fp); return 1; }

    struct reading r;
    if (fread(&r, sizeof r, 1, fp) != 1) {
        fprintf(stderr, "short read\n");
        fclose(fp);
        return 1;
    }
    printf("record %ld at byte %ld: id=%d sensor=%s value=%.1f\n",
           n, offset, r.id, r.sensor, r.value);

    fclose(fp);
    return 0;
}

Build and run

gcc -std=c11 -Wall -Wextra -o read_nth read_nth.c
./read_nth 4
./read_nth 1
./read_nth 9

Expected output

record 4 at byte 60: id=4 sensor=light value=340.0
record 1 at byte 0: id=1 sensor=temp value=24.5
record 9 out of range (file has 6)

The third run goes to standard error and the program exits with status 1. This is the behavior you want from tools used in scripts.

Why fread() Returns a Count, Not a Byte Total

fread(ptr, size, nmemb, fp) returns the number of complete items read. We ask for one item, so success means a return of 1. A return of 0 means end of file or a partial record. Comparing to 1 is the correct check. Comparing to sizeof r is a classic beginner bug.

CallReturns on successGood check
fread(&r, sizeof r, 1, fp)1== 1
fread(buf, 1, 20, fp)20== 20
fwrite(&r, sizeof r, 1, fp)1== 1

Real-World Use Cases

  • A host tool that shows a single entry from a large binary sensor log.
  • A test harness that replays packet number n from a capture file.
  • A settings store where each slot is a fixed-size record addressed by index.

Common Mistakes and Troubleshooting

Off-by-one numbering. If you seek to n * sizeof instead of (n - 1) * sizeof you read the next record. The first record is at offset 0.
Changing the structure and keeping the old file. Adding a field changes the record size, and old files become unreadable. Version your files or add a header.
Assuming the file is portable. Writing a raw structure includes compiler padding, byte order of integers and float format. A file written on one CPU may not read correctly on another. For firmware that exchanges files between devices, define the layout field by field and convert byte order yourself.
Using a text mode. Open with “rb” and “wb”.

Best Practices, Performance and Security

  • Validate the record number before seeking. Never trust a number from input or from inside another file.
  • Use strtol() instead of atoi() so you can detect bad input.
  • Read several records at once with a larger nmemb when scanning, because each seek discards the buffer.
  • Consider a small header with a version and record count so tools know what they are reading.

Practice Exercises for Your Free C Programming Course

Use these exercises to extend the reader from this free C programming course lecture. Each one adds a skill you will use in real projects.

  1. Add a second command line option so the program prints a range of records, for example records 2 to 5, with one seek and one fread() call that reads several records at once.
  2. Write a function long record_count(FILE *fp) that returns the number of records and restores the original pointer position.
  3. Add a field to the structure, rebuild both programs, and notice what happens when you read the old file. Explain the result.
  4. Print the last record without asking the user for its number, using only SEEK_END.
TaskOffset to seek to
Record 10
Record 340 for 20 byte records
Last record-20 from SEEK_END
Record n(n – 1) * 20

If you can finish all four, you have mastered the core of random access in this free C programming course and are ready for the update lab at the end of the chapter.

Summary and Key Takeaways

  • Offset of record n is (n – 1) times the record size.
  • Seek to the end and use ftell() to learn the file size and record count.
  • fseek() then fread() fetches one record directly.
  • Check both the seek and the read return values.

Conclusion: Free C Programming Course Next Steps

You have now built a complete random-access reader, the core skill behind many tools in embedded C programming. The next lecture of this free C programming course digs into ftell() and rewind(), the two helpers that make position handling easy to debug.

Frequently Asked Questions

How do I read the nth record of a file in C?

Compute (n – 1) times the record size, call fseek() with SEEK_SET, then fread() one record.

Why must records be the same size?

Fixed size makes the offset a simple multiplication. Variable-length records need an index.

How do I count records in a file?

Seek to the end, call ftell(), and divide by the record size.

Is it safe to write a struct directly with fwrite()?

On one machine and one compiler, yes. Across platforms, padding and byte order can differ.

What should I check after fread()?

That it returned the number of items you asked for.

Why use “rb” instead of “r”?

Binary mode avoids line-ending translation and keeps offsets exact.

Free Embedded C Course: Keep Going

Next: ftell() and rewind() explained with a live pointer trace.

PREV_LEC | NEXT_LEC

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

2 Comments

Leave a Reply

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

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →