[英]read, write, and as_bytes function
In Programming and principles chapter 11, the author gives the following code to demonstrate binary i/o:在编程与原理第11章中,作者给出了如下代码来演示二进制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:我有一些问题:
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. x
被传递给未初始化的函数,但x
的 undefined 值不会被使用。
The read
function is going to use the space allocated to x
as a container. read
函数将使用分配给x
的空间作为容器。 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.它将从
ifs
读取一个int
值的数据并将其存储在x
,为x
一个可以安全使用的已知值。 Because the body of the loop will not enter unless an int
was read from the file因为循环体不会进入,除非从文件中读取了一个
int
v.push_back(x);
is guaranteed to have a valid value for x
.保证
x
具有有效值。 That's assuming the input file contains valid int
s.那是假设输入文件包含有效的
int
s。
ifs
is being read in blocks of int
size. ifs
正在以int
大小的块读取。 If the size of the file is not evenly divisible by the size of an int
the final read
will fail.如果文件的大小不能被
int
的大小整除,则最终read
将失败。 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.只有在
read
成功时才进入循环体,因此不会向向量添加任何数据,也不会从vector
读取任何数据并将其写入输出文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.