ADVANCED DATA STRUCTURES PROGRAM • LEVEL 19 — FILES AND FILE ORGANIZATION

Pack Variable-Length Records with Length Prefixes

Learn how to pack variable-length records with length prefixes using a clear C program.

AdvancedRecord organizationSecondary storage

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Ada Bhavya Ravi

COMPLETE C PROGRAM

Complete C implementation

ads-variable-length-record-packing.c
Open in compiler
#include <stdio.h>
#include <string.h>

int main(void)
{
    const char*names[]={"Ada","Bhavya","Ravi"};FILE*file=fopen("variable.bin","wb+");if(!file)return 1;for(int i=0;i<3;i++){int length=(int)strlen(names[i]);fwrite(&length,sizeof length,1,file);fwrite(names[i],1,(size_t)length,file);}rewind(file);for(int i=0;i<3;i++){int length;char name[20];fread(&length,sizeof length,1,file);fread(name,1,(size_t)length,file);name[length]='\0';printf("%s%c",name,i==2?'\n':' ');}fclose(file);return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Ada Bhavya Ravi
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Write each payload after its length so a reader can locate the following record safely.
  3. Display the computed result.

Write each payload after its length so a reader can locate the following record safely.

EFFICIENCY

Time and space complexity

Time complexity

O(total record bytes)

Auxiliary space

O(maximum record length)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.