CSE 2341 Object Oriented Programming with C Note Set 15 1 Overview Review of Binary File I O Random File I O 2 File I O 3 steps open the file read write using the file close the file Binary File I O Open the file using ios binary use the read and write functions to write char pointer that points to first byte of structure to the read written 3 Quick Example include iostream include fstream using namespace std struct personInfo char name 15 int age int main personInfo pi 4 Bob 22 Sally 23 Sam 24 Pat 25 fstream fOut myFile dat ios out ios binary 4 Quick Example if fOut cout Error endl return 0 for int i 0 i 4 i fOut write reinterpret cast char pi i sizeof personInfo fOut close return 0 5 Problem You want to read the 3rd record out of the file without having to read the first two Remember there are pointers in the file object that maintain state it knows you are currently reading and writing in the file you can manipulate these via member functions called using your file objects 6 seekp fObj seekp 32L ios beg sets the write position to the 33rd byte byte 32 from the beginning of the file fObj seekp 10L ios end sets the write pos to the 11th byte byte 10 from the end of the file fObj seekp 120L ios curr sets the write pos to the 121st byte byte 120 from the current position 7 seekg fObj seekg 2L ios beg sets the read position to the 3rd byte 2 from the beginning of the file fObj seekg 100L ios end sets the read position to the 101st byte byte 100 from the end of the file fObj seekg 40L ios curr sets the read position to the 41st byte byte 40 from the current position fObj seekg 0L ios end sets the read position to the end of the file 8 Simple Write include iostream include fstream using namespace std int main fstream fout data dat ios out ios binary char c A while c K fout write c sizeof c c data dat fout close ABCDEFGHIJ return 0 9 Reading with Random Functions int main fstream fin data dat ios in ios binary char a fin get a cout a endl fin seekg 3 ios beg fin get a cout a endl fin seekg 4 ios end fin get a cout a endl fin seekg 2 ios cur fin get a cout a endl return 0 OUTPUT A D G J data dat ABCDEFGHIJ 10 See Lecture 15 Handout for a More Robust example 11 Fini 12
View Full Document
Unlocking...