Task: Write a C++ – CPP Program to write / add records in Binary File.
How this Program Works?
This C++ Program will open a binary file either by creating a new file or by just opening it if it already exists. Then it will use write() method to write for first time or append more records in the existing file. It is because we have opened the file in append mode as follows:
//opening binary file in appending / writing mode
The following figure shows that the file cpppfile.dat has been created on D drive after execution f the C++ program.
First of all a user will input a record and it is written into binary file using write()method as follows:
/* write a record to binary file */
Then program will ask from the user: Add more records? press y or n:
The user will press ‘y’ if he wishes to add more records. Otherwise he will type ‘n’, if he wishes to stop the program. This input logic is maintained by a while loop.
Source code for the C ++ program to enter records in a binary file.
A Sample Run of the C++ Program: write / add records in Binary File
Enter Student Record Roll No:101 Name:sajid Record has been added successfully Add more records? press y or n =y Enter Student Record Roll No:102 Name:majid Record has been added successfully Add more records? press y or n =n Program ended: C++ Program To Add more Student Records in Binary File: -------------------------------- Process exited after 41.99 seconds with return value 0 Press any key to continue . . .