C++ 读、写和as_字节函数

C++ 读、写和as_字节函数,c++,C++,在编程和原理第11章中,作者给出了以下代码来演示二进制i/o: #include<iostream> #include<string> #include<vector> #include<algorithm> #include<cmath> #include<sstream> #include <fstream> #include <iomanip> using namespace std;

在编程和原理第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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
模板
char*as_bytes(T&i)//将T视为字节序列
{
void*addr=&i;//获取第一个字节的地址
//用于存储对象的内存的大小
返回static_cast(addr);//将该内存视为字节
}
int main()
{
//打开文件中二进制输入的istream:
在南部;
ifstream ifs{iname,ios_base::binary};//注意:流模式
//二进制告诉流不要尝试任何巧妙的字节操作
//打开ostream以将二进制输出到文件:
库特·奥纳姆;
of流{oname,ios_base::binary};//注意:流模式
//二进制告诉流不要尝试任何巧妙的字节操作
向量v;
//从二进制文件读取:
for(int x;ifs.read(作为_字节(x),sizeof(int));//注意:读取字节
v、 推回(x);
//…用v做点什么。
//写入二进制文件:
用于(整数x:v)
write(作为_字节(x),sizeof(int));//注意:写入字节
返回0;
}
我有一些问题:

  • 他为什么要读取未初始化变量的地址
  • 为什么程序会在文件末尾截断一些字符
  • 他为什么以及如何将未初始化的变量推到向量
  • 问题1和3 在

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

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

    v.push_back(x);
    
    保证具有
    x
    的有效值。假设输入文件包含有效的
    int
    s

    问题2
    正在以
    int
    大小的块读取
    ifs
    。如果文件大小不能被
    int
    整除,则最终的
    读取将失败。只有在
    读取
    成功时,才会进入循环体,因此不会将任何数据添加到向量,也不会从
    向量
    读取任何数据并写入输出文件。

    作为字节
    也可以直接转换为
    字符*
    。严格的别名保证所有对象都可以作为字节数组查看。无需中途停留在
    void*
    。在c++二进制中处理二进制数据的一些棘手的细微差别可能非常令人讨厌。那个,那个。。。与第一次将
    std::string
    写入文件时所获得的惊喜相比,它们算不了什么。为什么不直接使用
    reinterpret\u cast
    v.push_back(x);