TAILIEUCHUNG - Object Oriented Programming (30)

CSC241: Object Oriented Programming. Lecture No 32. 1 Previous Lecture.• Stream and classes. •. Input and Output stream. •. iostream class. •. ios class. – Formatting Flags. – Error-Status Bits. – Formatted File I/O. ». Reading data. ». Writing data 2 Today’s Lecture.• File operations.• Formatted File I/O. •. Reading data. •. Writing data. •. Character I/O.• Binary I/O.• Object I/O 3 Character I/O.•. put() and get() functions, can be used to output. and input single characters.•. These are member of ostream and istream,. respectively. Go to. program.•. Another way is to use rdbuf() function. ifstream infile(“”);. cout (buff),.MAX*sizeof(int) );.•. Opening file in read mode. ifstream is(“”, ios::binary);.•. Reading whole array in buff from is ( reinterpret_cast(buff),.MAX*sizeof(int) ); 6 reinterpret_cast operator.•. It is used to make it possible for a buffer of type. int to look to the read() and write() functions like. a buffer of type char.•. It changes the type of a section of memory. Go to. program. 7 Object I/O.•. An object’s values can be written in and read. back from a file.•. Generally binary mode is use for Object I/O. – This writes the same bit configuration to disk that was. stored in memory, and. – ensures that numerical data contained in objects is. handled properly.•. Example program. – Input value from user in an object of class person. – writes this object to the disk file. 8 Writing/reading an Object to person {. protected:. char name[40];. int age;. public:. void getData() {. cout >. Go ;. program. cout > age;. }.};.main() {. person pers;. ();. ofstream outfile(“”, ios::binary);. (reinterpret_cast(&pers),.sizeof(pers)); 9 Compatible Data Structures.•. Reading and writing object can. – belong to same class of objects. – or if classes are different then they must have same. data members (without virtual functions).•. Person class object occupy 40 + 4 = 44 bytes.•. Make sure a class used to read an object is. identical to the class used to write it•. Also do not attempt disk I/O with objects

TỪ KHÓA LIÊN QUAN
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.