- Reading and writing binary files is subtly different
than text files, especially if you want to support
an operating system that distinguishes between text files
and binary files.
This is a working copy
of file-io-struct.cpp
from chapter eight of the exercise files.
And what we're doing here,
is we're taking this data structure,
which includes a couple of integers and a C string.
And we're going to write it to a file
and then read it from that file
and then parse it back out into the data structure.
So, this is actually a lot simpler than it sounds.
Here we open the file and you'll notice
that we use the B, after the W.
This is for binary mode.
Some operating systems,
including Microsoft Windows translate line endings
and text files.
Without the B, such an operating system may assume
that the file is text
and may translate what it sees
as line endings for you,
which will alter the file,
unless you tell the operating system
that it's a binary file, with this B flag.
This B flag indicates binary mode tells the system
not to translate line endings.
The binary flag is generally ignored on systems
where it's not required,
and so it doesn't hurt anything if you use it,
whenever you work with non-text files.
Here we declare a static buffer of type S one,
which is our structure,
which we defined up here.
We populate it with an integer,
with the length of the string,
and we make sure the length is not greater
than our max length which we declared up
at the top there in line seven.
And we copy the string into the buffer,
we make sure it's terminated, and then we write it.
And we're using fwrite in this case.
And we're writing from our buffer,
and because our buffer is a structure,
it's not an array,
we need to use the address of operator.
And we tell it the size of the buffer.
How many of them there are, and the file handle.
And then we do this five times obviously,
we close the file and we puts done,
and then we read the file.
And now here we are reading the file again
with the binary flag,
we have another static buffer,
and we use fread now to read chunks
in the size of the buffer,
from our file handle.
And then once we have the data in the buffer,
we simply printed out using the dot notation
to dereference the members of the structure.
So this is very simple really.
Then we close and we remove the file and we're done.
So let's go ahead and build and run.
And you see, we write the file.
We're done.
We read the file and here we have each of our integers,
and our strings.
And so this works exactly as we expect.
If you want to support Microsoft windows
or other operating systems that treat text files differently
than binary files,
you'll want to use the B flag whenever working
with non-text files.