binary fstream Flashcards
(6 cards)
What’s the difference in size between a binary file and a regular file if you were trying to store the number 8432
In a regular file this would take up 1 byte for each character, in a raw binary file though this would only take 2 bytes
Why would writing to a binary file from an array be faster than writing to a regular file?
A binary file would allow you to just write the entire array in one write function rather than putting it in piece by piece with a loop.
Add the number 8675 to a binary file
ofstream defaults to regular file so we’ll use fstream
std::fstream fout;
unsigned short x = 8675
fout.open(“file.dat”, ios::out | ios::binary)
if (fout)
{
fout.write(reinterpret_cast<char*>(&x), sizeof(unsigned short));
fout.close();
}
else
cout «_space;“Error opening file\n”
reinterpret_cast<char*>(&x) < this changes x into a character memory address
fout.write(reinterpret_cast<char*>(&x), sizeof(unsigned short)); < - This grabs 2 bytes from the memory address of x and dumps it into file.dat
Open a file for reading in binary
fout.open(“file.dat”, ios::in | ios::binary);
if (fout)
{
unsigned short y;
fout.read(reinterpret_cast<char*>(&y), sizeof(unsigned short))
}
else
cout «_space;“Error opening file!\n”
Video
https://www.youtube.com/watch?v=fCvJ9Rsfy6c