读取、写入和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 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 和 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
读取任何数据并将其写入输出文件。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 文件系统:复制功能的速度秘诀是什么
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 如何在Directwrite中获得给定字体的可用OpenType功能
- 对可变参数使用声明.如何选择正确的功能
- 询问在设计我的手臂模拟器功能表示格式1
- 功能原型的目的
- 这里在 Linux 中具有"CreatePipe"和"CreateProcessW"功能吗?