C PROGRAMMING PROGRAM • FILE HANDLING
Write and Read a Structure in a Binary File
Learn how to write and read a structure in a binary file using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
101 Anu 92.5
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
struct Record { int id; char name[20]; double marks; };
int main(void)
{
struct Record original = {101, "Anu", 92.5};
struct Record restored = {0};
FILE *file = fopen("record.bin", "wb");
if (file == NULL) return 1;
if (fwrite(&original, sizeof original, 1, file) != 1) { fclose(file); return 1; }
fclose(file);
file = fopen("record.bin", "rb");
if (file == NULL) return 1;
if (fread(&restored, sizeof restored, 1, file) != 1) { fclose(file); return 1; }
fclose(file);
printf("%d %s %.1f\n", restored.id, restored.name, restored.marks);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
101 Anu 92.5
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Write the structure bytes as one record and restore the same record with fread.
- Display the computed result.
Write the structure bytes as one record and restore the same record with fread.
EFFICIENCY
Time and space complexity
Time complexity
O(1)
Auxiliary space
O(1)
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.
