读取、写入和as_bytes功能

read, write, and as_bytes function

本文关键字:bytes 功能 as 读取      更新时间:2023-10-16

在编程和原理第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 namen";
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 namen";
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;
}

我有一些问题:

  1. 他为什么要读取未初始化变量的地址?
  2. 为什么程序会在文件末尾截掉一些字符?
  3. 他为什么以及如何将未初始化的变量推送到向量?

问题 1 和 3

for(int x; ifs.read(as_bytes(x),sizeof(int)); )

x被传递到未初始化的函数中,但x的未定义值不会被使用。

read函数将使用分配给x的空间作为容器。它将从ifs中读取一int的数据并将其存储在x中,给x一个已知的值,然后可以安全地使用。因为除非从文件中读取int,否则循环的主体不会进入

v.push_back(x);

保证具有x的有效值。这是假设输入文件包含有效的int

问题2

ifs正在int大小的块中读取。如果文件大小不能被int大小整除,则最终read将失败。仅当read成功时,才会进入循环的主体,因此不会向向量添加任何数据,也不会从vector读取任何数据并将其写入输出文件。