QUESTION 09
How does a sequential record-file search work?
2 marksAnswer
Read each complete record and compare its key with the requested key until a match or end is reached. It does not require sorted records.
QUESTION 09
Read each complete record and compare its key with the requested key until a match or end is reached. It does not require sorted records.
QUESTION 10
A simple record database is a file of records whose fields include a key, such as a student ID.
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.
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.
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.
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.
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.
/* 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(¤t, 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;
}The example uses values in the code.
Roll = 102, marks = 85