Reputation: 79
In Programming and principles chapter 11, the author gives the following code to demonstrate binary i/o:
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<sstream>
#include <fstream>
#include <iomanip>
using namespace std;
template<class T>
char* as_bytes(T& i) // treat a T as a sequence of bytes
{
void* addr = &i; // get the address of the first byte
// of memory used to store the object
return static_cast<char*>(addr); // treat that memory as bytes
}
int main()
{
// open an istream for binary input from a file:
cout << "Please enter input file name\n";
string iname;
cin >> iname;
ifstream ifs {iname,ios_base::binary}; // note: stream mode
// binary tells the stream not to try anything clever with the bytes
// open an ostream for binary output to a file:
cout << "Please enter output file name\n";
string oname;
cin >> oname;
ofstream ofs {oname,ios_base::binary}; // note: stream mode
// binary tells the stream not to try anything clever with the bytes
vector<int> v;
// read from binary file:
for(int x; ifs.read(as_bytes(x),sizeof(int)); ) // note: reading bytes
v.push_back(x);
// . . . do something with v . . .
// write to binary file:
for(int x : v)
ofs.write(as_bytes(x),sizeof(int)); // note: writing bytes
return 0;
}
I have some questions:
Upvotes: 3
Views: 445
Reputation: 33932
In
for(int x; ifs.read(as_bytes(x),sizeof(int)); )
x
is passed into the function uninitialized, but x
's undefined value is not going to be used.
The read
function is going to use the space allocated to x
as a container. It will read one int
's worth of data from ifs
and store it in x
, giving x
a known value that can then be safely used. Because the body of the loop will not enter unless an int
was read from the file
v.push_back(x);
is guaranteed to have a valid value for x
. That's assuming the input file contains valid int
s.
ifs
is being read in blocks of int
size. If the size of the file is not evenly divisible by the size of an int
the final read
will fail. The body of the loop is only entered if the read
is successful, so no data is added to the vector and no data will be read from the vector
and written to the output file.
Upvotes: 2