Task: Copy All Records to Another File Program in C Plus Plus
This program will open the source file in reading ( in ) mode. It will open the destination file in writing (out) mode. Then the program will read all records from source file one by one. And copy every record to destination file.
This record copy process is in a while loop. It will continue to copy records as long as end of file (source file) is not reached.
Finally, this C++ file copy program will display a message: ‘File Copied successfully’ etc.
The source code of Copy All Records to Another File Program in C Plus Plus
/* Write a C++ Program to copy all records of a binary file 'cppfile.dat' into'copyfile.dat' */ #include<iostream> #include<fstream> #include<conio.h> #include<stdlib.h> #include<string> using namespace std; struct student { int rollno; char name[30]; }srecord; int main() { char ans; fstream file1, file2; //opening source binary file in writing mode // if we run this program again, it will //overwrite the destination file file1.open("d://cppfile.dat",ios::binary |ios::in); if(!file1) { cout<<"Source File could not open"; exit(0); } //opening destination binary file in reading mode file2.open("d://copyfile.dat",ios::binary |ios::out); if(!file2) { cout<<"Destination File could not open"; exit(0); } while(!file1.eof()) { file1.read((char*)&srecord,sizeof(srecord)); if(!file1.eof()) file2.write((char*)&srecord,sizeof(srecord)); } file1.close(); file2.close(); cout<<"\nFile copied successfully.\n Thanks for visiting www.EasyCodebook.com"; return 0; }
A sample run output :C++ Program to copy all record from binary file to another file
Output:
File copied successfully.
Thanks for visiting www.EasyCodebook.com
——————————–
Process exited after 4.238 seconds with return value 0
Press any key to continue . . .
Pingback: Python File Phonebook Program | EasyCodeBook.com