File Update Lesson xx
description
Transcript of File Update Lesson xx
Slide 1
File Update Lesson xx
In this module, well talk about updating files.1ObjectivesWorking with multiple filesCopying files Updating files
In this presentation, well put all the material that we learned about random access files together in one program. Well cover the following topics: working with multiple files, copying files, and updating files. 2Data FilesHelen10Julie20Annie40Lena30May50Alan60
Julie34Sam18Lena55Lee43Helen15
Helen10Julie20Annie40Lena30May50Alan60
masterc.datmaster.dattrans.dat
In the next program we want to show you how to update files. Well be working with these 3 files: master.dat, masterc.dat and trans.dat. Think of it this way, master.dat might be used to store year to date information. In other words, Helen has earned $10 so far this year, Julie has earned $20 year to date etc. Looking at trans.dat, we might use that file to record the employees pay for the week. So, in this example, Julie earned $34 this week, Sam made $18 this week. Since you dont want to mess up your master file, we make a copy of master.dat onto masterc.dat.3Program DescriptionOpen 3 files: master.dat, trans.dat, masterc.dat
Make a copy of master.dat on masterc.dat
Read in the 3rd record of trans.dat
Find the record on masterc.dat with the same name as the 3rd transaction record.
Add the amount from the transaction record to the amount in the master record
Write the updated record onto masterc.dat
Heres what were going to do in the next program. 1) Open 3 files: master.dat, trans.dat,masterc.dat 2) Make a copy of master.dat onto masterc.dat 3) Read in the 3rd record of trans.dat 4) Find the record on masterc.dat with the same name as the 3rd transaction record. 5)Add the amount from the transaction record to the amount in the master record 6)Write the updated record onto masterc.dat
4Updated FileHelen10Julie20Annie40Lena30May50Alan60
Julie34Sam18Lena55Lee43Helen15
Helen10Julie20Annie40Lena85May50Alan60
masterc.datmaster.dattrans.dat
Here is a picture of what the files look like when we finish this program. master.dat and trans.dat remain the same. Since Lena made $30 year to date and for this pay period she made $55 , she now has made a total of $85. In real life, you would update every record, not just the 3rd record.5Program Listing Part 1#includeusing std::fstream;using std::ios;#include using std::cout;using std::endl;#includestruct record { char name[15]; float amt; };
This is part 1 of the program where we have the preprocessor directives and the structure definition. 6Program Listing Part 2 int main() {fstream mf("master.dat",ios::in | ios::binary);fstream mc("masterc.dat",ios::out | ios::binary); //Copy of masterfstream tf("trans.dat",ios::in | ios::binary);record master,trans;//Copy master file onto mastercwhile ( mf.read((char *)&master,sizeof(master))) { cout