[英]read, write, and as_bytes function
在编程与原理第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;
}
我有一些问题:
在
for(int x; ifs.read(as_bytes(x),sizeof(int)); )
x
被传递给未初始化的函数,但x
的 undefined 值不会被使用。
read
函数将使用分配给x
的空间作为容器。 它将从ifs
读取一个int
值的数据并将其存储在x
,为x
一个可以安全使用的已知值。 因为循环体不会进入,除非从文件中读取了一个int
v.push_back(x);
保证x
具有有效值。 那是假设输入文件包含有效的int
s。
ifs
正在以int
大小的块读取。 如果文件的大小不能被int
的大小整除,则最终read
将失败。 只有在read
成功时才进入循环体,因此不会向向量添加任何数据,也不会从vector
读取任何数据并将其写入输出文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.