binary fileio notes

binary fileio notes - cout<< temp<< endl fin.close...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Binary FileIO ----------------- CHAPTER 17 Write/read byte for byte to and from memory stream of data is binary instead of character In order to open a file for binary writing/output: ofstream fout; fout.open("data.dat", ios::binary | ios::out); //note: not using a stream insertion operator int x=37; fout.write(reinterpret_cast<char*>(&x), sizeof(int)); fout.close(); /* Allows you to on the fly convert pointer types sizeof(int) tells it how many bytes to write uses char* because they are stored byte byte byte instead of chunks of bytes like an int* */ In order to read from a binary file fstream fin("data.dat", ios::binary | ios::in); // uses the || thing not L or 1 int temp; fin.read(reinterpret_cast<char*>(&temp), sizeof(int));
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: cout << temp << endl; fin.close(); Allows user to change data without reading the entire file, changing it, then writing the entire file back Structured Data struct data{ int freq; int id; }; //just like a class but default visibility of a structure is public //implement binary fileio int main(){ data d; d.freq=26; d.id=19; fstream fout("info.dat", ios::binary | ios::in); fout.write(reinterpret_cast<char*>(&d),sizeof(data)); fout.close(); return 0; } int main(){ data temp; fstream fin; fin.open("info.dat", ios::binary|ios::in); reads from file and inputs into temp # of bytes in a data object fin.read(reinterpret_cast<char*>(&temp), sizeof(data)); structure temp now contains the data from file cout<< temp.freq<<endl; fin.close(); return 0; }...
View Full Document

{[ snackBarMessage ]}

Page1 / 2

binary fileio notes - cout<< temp<< endl fin.close...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online