繁体   English   中英

读、写和 as_bytes 函数

[英]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;
}

我有一些问题:

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

问题 1 和 3

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM