1. 程式人生 > >C++ ifstream,ofstream讀寫二進位制檔案

C++ ifstream,ofstream讀寫二進位制檔案

為什要吧資料存為二進位制

這個嘛,是我個人習慣,一般,我們會把日誌檔案存為文字檔案。資料檔案存成二進位制檔案。

其實,我們接觸的檔案,比如影象、視訊都是以二進位制的形式儲存的,要想檢視這類資料,必須知道資料是如何儲存的。

不管你的資料型別是什麼,以二進位制形式儲存的時候,都可以把它以位元組的形式儲存。

比如int,也許有四個位元組,我們只需要把它的地址換成char×,並且寫入4個位元組就行了,讀出也是一樣的。

程式碼

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char** argv)
{

  int a[5] = {1,2,3,4,5};
  int b[5];

  ofstream ouF;
  ouF.open("./me.dat", std::ofstream::binary);
  ouF.write(reinterpret_cast<const char*>(a), sizeof(int)*5);
  ouF.close();

  ifstream inF;
  inF.open("./me.dat", std::ifstream::binary);
  inF.read(reinterpret_cast<char*>(b), sizeof(int)*5);
  inF.close();

  for (int i = 0; i < 5; i++)
  {
    cout << b[i] << endl;
  }
  return 0;
}