Skip to study material
← Question index

QUESTION 10

Explain searching a file-based record database by key.

5 marks

Answer in brief

A simple record database is a file of records whose fields include a key, such as a student ID.

Algorithm

  1. Open the file in the format used to create it.
  2. Read one complete record.
  3. Compare its key with the requested key.
  4. On a match, display the record or return its location.
  5. Otherwise continue; distinguish not-found from an input error.

Example

The demonstration writes three native Student records and searches for ID 102. It reads record 101 first, then finds 102 and displays that record’s mark. This is a linear search on file records. It stops without requiring the records to be sorted.

Missing and repeated keys

If every read succeeds until normal end and no key matches, report Not found. Decide whether duplicate keys are forbidden, whether the first match is enough or whether all matches should be displayed. A first-match algorithm should not claim to list every duplicate.

Design limitations

Use a stable defined record format for a real shared database. Native structure dumping can include padding and implementation-dependent representation, so the sample is local teaching code. Text records need parsing and validation instead. An index can speed repeated access but is a separate data structure with maintenance costs.

Complexity

A first-record match needs O(1) record comparisons. An absent key or last-record match requires O(n). Only one record buffer is necessary, giving O(1) auxiliary record space. Actual I/O latency also depends on buffering and the storage system.

Complete C example

This demonstration creates or replaces its codebhavya_* sample file in the working directory. Run it in a separate test directory. Native binary examples use one compatible implementation.

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
struct Student { int roll, marks; };

int main(void)
{
    struct Student records[3] = {{101, 70}, {102, 85}, {103, 80}}, current;
    FILE *fp = fopen("codebhavya_records_demo.bin", "wb");
    if (fp == NULL) { puts("Open failed"); return 1; }
    if (fwrite(records, sizeof records[0], 3, fp) != 3) { fclose(fp); puts("Write failed"); return 1; }
    if (fclose(fp) != 0) { puts("Close failed"); return 1; }
    fp = fopen("codebhavya_records_demo.bin", "rb");
    if (fp == NULL) { puts("Open failed"); return 1; }
    int found = 0;
    while (fread(&current, sizeof current, 1, fp) == 1) {
        if (current.roll == 102) { printf("Roll = %d, marks = %d\n", current.roll, current.marks); found = 1; break; }
    }
    int failed = ferror(fp);
    if (fclose(fp) != 0 || failed) { puts("Read/close failed"); return 1; }
    if (!found) { puts("Not found"); }
    return 0;
}

Sample input and output

The example uses values in the code.

Output

Roll = 102, marks = 85