开发者社区> 问答> 正文

读取、写入和AS_字节函数

在第11章的编程和原则中,作者给出了以下代码来演示二进制:

#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;
}

我有一些问题:

为什么他要读取一个未初始化变量的地址? 为什么程序在文件末尾切断了一些字符? 为什么以及如何将未初始化的变量推送到向量中?

展开
收起
aqal5zs3gkqgc 2019-12-06 21:11:40 990 0
1 条回答
写回答
取消 提交回答
  • 问题1和问题3 在……里面

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

    x传递给未初始化的函数,但是x未定义的值将不被使用。

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

    v.push_back(x);
    
    

    的有效值。x...假设输入文件包含有效的intS.

    问题2 ifs正在以块的形式读取int尺寸。如果文件的大小不能被int决赛read都会失败。只有在read成功,因此不会向向量中添加任何数据,也不会从vector并写入输出文件。

    2019-12-06 21:12:58
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载