120 likes | 258 Views
This guide provides an overview of Binary and Random File I/O in C++. It covers the three essential steps: opening a file, reading/writing data, and closing the file. Detailed examples demonstrate the use of binary file handling through the `fstream` library, including reading and writing structure arrays. Learn how to manipulate file pointers to access records efficiently, ensuring you can read data directly without processing preceding records. Ideal for students mastering Object-Oriented Programming in C++.
E N D
Overview • Review of Binary File I/O • Random File I/O
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
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);
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; }
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
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
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
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++; } fout.close(); return 0; } data.dat ABCDEFGHIJ
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
See Lecture 15 Handout for a More Robust example
Fini ?