sequential-access file Create, read and write an object into a sequential-access file Serialize and deserialize the object to write and read from a data file The class must be defined as serializable For example, class record contain four data members
Record public __gc class Record { [Serializable] private: int account; String* firstname; String *lastname; double balance; public: ……. };
Creating Sequential-Access File Serializable attribute indicates to the compiler that objects of a class can be serialized– written to or read from a stream as objects. Objects that we wish to write to or read from a stream must include this attribute in their class definition Objects Attributes are identifiers ( within square brackets ) that specify additional information in a declaration. The code that defines an attribute is applied at runtime.
Open a file We can open files for manipulation by creating objects of classes FileStream. FileStream constructor can receive three arguments A String * containing the name of the file to be opened A constant describing how to open the file A constant describing the file permission FileStream *output = new FileStream( filename, FileMode::OpenOrCreate, FileAccess::Write);
Write record to FileStream (serialize object) private: static BinaryFormatter *format = new BinaryFormatter(); format->Serialize(output, record); Output is FileStream object record is a Record object Record record;
Read from file Create FileStream to obtain read access to file private: FileStream *input; private: static BinaryFormatter *reader = new BinaryFormatter(); input = new FileStream(filename, FileMode::Open, FileAccess::Read);
Deserialize record and store data in TextBoxes try{ Record *record = dynamic_cast (reader->Deserialize(input) ); String *values[] = { record-> Account.ToString(), record->LastName->ToString(), record->FirstName->ToString(), record->Balance.ToString()}; }; SaveTextBox(values); }
catch( SerializationException *) { input->close(); … }
SaveFileDialog Create dialog box enabling user to save file SaveFileDialog *filechooser = new SaveFileDialog(); Windows::Forms::DialogResult res = filechooser->ShowDialog(); Get specified file name String filename = filechooser->FileName;
OpenFileDialog Create dialog box enabling user to open file OpenFileDialog *filechooser = new OpenFileDialog(); Windows::Forms::DialogResult res = filechooser->ShowDialog(); Exit event if clicked cancel if( res == DialogResult::Cancel) return; Get specified file name String *filename = filechooser->FileName;