Kook-Jin Yeo
Kook-Jin Yeo

Reputation: 85

c++ reading integers from binary file, missing some data

I am saving 100,000 integers to a binary file using:

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

and from this file, I'm trying to read integers, and save them into a vector.

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++;
}

However it seems like I can only read 99328 integers, not 100000. I am relatively new with read/write with binary files, so can you guys help me?

Upvotes: 0

Views: 357

Answers (2)

Ap31
Ap31

Reputation: 3324

Looks like the file object is still open when the reading commences, which results in the described behavior.

Try calling file.close() to flush the buffer and only after that initialize ifile.

Also you will find that reading the whole vector at once can considerably speed up the process.

Upvotes: 2

cbuchart
cbuchart

Reputation: 11575

It's working for me. May be you forgot to use the ios::binary flag or to close the streams?

#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;
}

Upvotes: 2

Related Questions