binary fstream Flashcards

(6 cards)

1
Q

What’s the difference in size between a binary file and a regular file if you were trying to store the number 8432

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why would writing to a binary file from an array be faster than writing to a regular file?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Add the number 8675 to a binary file

A

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 &laquo_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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Open a file for reading in binary

A

fout.open(“file.dat”, ios::in | ios::binary);
if (fout)
{
unsigned short y;
fout.read(reinterpret_cast<char*>(&y), sizeof(unsigned short))
}
else
cout &laquo_space;“Error opening file!\n”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Video

A

https://www.youtube.com/watch?v=fCvJ9Rsfy6c

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly