簡體   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