int 類型的數值一次性寫入一次性讀取

來源:互聯網
上載者:User

標籤:c++

將一個20M 的int數值一次性保持,並一次性讀取,避免儲存為char 類型,進行格式轉換的時候很耗時。


#include <iostream>#include <fstream>#include <time.h>using namespace  std;#define  MAXNUM  2560*1920void savedata(char *filename,int *pdata){ofstream out;out.open(filename,ios::binary);if(!out.is_open())return ;for (int i=0;i<MAXNUM;i++){pdata[i] = i;}out.write((char *)pdata,MAXNUM*sizeof(int));out.close();cout<<endl;}void readdata(char *filename,int *pdata,int length){ifstream ifs(filename,ios::binary);if (!ifs){cout << "File open error!" << endl; exit(1);}// 擷取檔案大小。ifs.seekg(0, ios::end);streampos pos = (ifs.tellg());ifs.seekg(0, ios::beg);  // 注意要將檔案指標移動到檔案頭if (pos > 0){ifs.read((char*)pdata, pos);for (int i = 0; i < pos/4; i++){cout << pdata[i];cout << endl;}}ifs.close();}void main(){int  *pd = new int[MAXNUM];memset(pd,'0',MAXNUM);for (int i=0;i<MAXNUM;i++){pd[i] = i;}savedata("datat.img",pd);int* buff = new int[MAXNUM];memset(buff,'0',MAXNUM);double start=clock();readdata("datat.img",buff,MAXNUM);double end=clock();cout<<(end - start)<<endl;system("pause");}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.