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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Ada Bhavya Ravi
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Ada Bhavya Ravi
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Write each payload after its length so a reader can locate the following record safely.
- 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.
