2017-02-26 3 views
0

が欠落し、バイナリファイルから整数を読み込む:C++、私が使用してバイナリファイルに10万整数を保存していますいくつかのデータに

for(unsigned int i = 0; i < 100000; i++){ 
     temp = generateRand(99999); 
     file.write(reinterpret_cast<const char*>(&temp),sizeof(temp)); 
    } 

と、このファイルから、私は整数を読み、そしてベクターにそれらを保存しようとしています。

ifstream ifile; 
ifile.open("test.bin",ios::binary); 

ifile.seekg(0, ifile.end); 
long size = ifile.tellg(); 
ifile.seekg(0, ifile.beg); 

int restore = 0; 
int count = 0; 

while(ifile.tellg() < size){ 
    ifile.read(reinterpret_cast<char*>(&restore), sizeof(restore)); 
    v.push_back(restore); 
    count++; 
} 

私は99328個の整数を読むことができるようにそれはそうしかし、ない100000私が読んで/バイナリファイルに書き込む比較的新しいですので、あなたたちは私を助けることができますか?

+0

「temp」の種類は何ですか?あなたが手に入れたファイルのサイズは? 'file'と' ifile'をどのように定義/オープンしますか? – Ap31

+0

ああ、温度はint型です。 generateRand関数はランダムな整数を生成するだけです。 –

+0

あなたは 'file'をクローズするか破棄しますか? – Ap31

答えて

2

読み取りが開始したときにfileオブジェクトがまだ開いているように説明した動作で、その結果、ルックス。

を呼び出すと、バッファをフラッシュしてから、その後で初めてifileに初期化してください。

また、ベクトル全体を一度に読み取ると処理が大幅に高速化されることがわかります。

+0

ありがとう!あなたが正しいです。 –

2

私のために働いています。 ios::binaryフラグを使用することやストリームを終了することを忘れていますか?

#include <vector> 
#include <fstream> 
#include <iostream> 

using namespace std; 

void write() { 
    ofstream file; 
    file.open("temp.data", ios::binary); 
    for(unsigned int i = 0; i < 100000; i++){ 
    int temp = 0; // I don't know the generateRandom(...) function 
    file.write(reinterpret_cast<const char*>(&temp),sizeof(temp)); 
    } 
} 

void read() { 
    ifstream ifile; 
    ifile.open("temp.data", ios::binary); 

    ifile.seekg(0, ifile.end); 
    long size = ifile.tellg(); 
    ifile.seekg(0, ifile.beg); 

    int restore = 0; 
    vector<int> v; 
    while(ifile.tellg() < size){ 
    ifile.read(reinterpret_cast<char*>(&restore), sizeof(restore)); 
    v.push_back(restore); 
    } 

    cout << v.size() << endl; 
} 

int main() 
{ 
    write(); 
    read(); 

    return 0; 
} 
+0

ありがとうございます。私はfile.close()を使ってバッファをフラッシュしなければなりません! –

+0

+1 - より良いプログラム構造は、出力ファイルが範囲外になったときに出力ファイルを自動的に閉じることによって問題を解決します。 –

+0

ああ、上記のwrite()やread()のような関数を使うと明示的にclose()関数を使わなければならないのですか? –

関連する問題