[英]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;
}
我有一些問題:
在
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.