Reputation: 1847
I am learning about C++ IO operations and have run into trouble reading from a binary file. I initialize an array with 100 random values, and write the values in the array to a .bin
file. I think I got that part down -for some reason though my .bin
file size is 1600 bytes instead of 400- but am struggling with reading the values.
I thought it was possible to read int by int by iterating through the memblock
array containing the read values, but my console output shows a single random number followed by a bunch of zeroes. I would appreciate your guidance.
// reading a binary file int by int
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
using namespace std;
int main () {
FILE * pFile;
streampos size;
int * memblock;
srand(time(NULL));
int array[100];
//data to write initially stored in array
for (int i=0;i<100;i++){
array[i]=rand()%100;
}
pFile = fopen("writebinary.bin","wb");
fwrite(array,sizeof(int),sizeof(array),pFile);
fclose(pFile);
ifstream readFile("writebinary.bin",ios::binary | ios::ate);
if (readFile.is_open()){
size = readFile.tellg();
//allocate memory to read file contents
memblock = new int[size];
readFile.seekg(0,ios::beg);
for (int i=0;i<100;i++){ //100 because there are 100 ints,I'm assuming 32 bits are read a at a time from writebinary.bin
readFile.read((char*)memblock,sizeof(int));
}
readFile.close();
}
else {
cout << "can't open file " << endl;
}
for (int i=0;i<100;i++){
cout << memblock[i] << endl;
}
return 0;
}
Upvotes: 0
Views: 470
Reputation: 932
Well, for your first issue, sizeof(array)
is 400, because your array of 100 ints takes up 400 bytes, and sizeof(int)
is 4, because an int is 32 bits. That's why you get a 1600 byte output file. You are hardcoding the number 100 everywhere else; you need to hardcode it here as well, or use sizeof(array)/sizeof(int)
.
Second, you don't need to iterate when using istream::read. It needs the size of the buffer to read, in bytes. So do readFile.read((char *)memblock,sizeof(array));
just once.
On another note, though, your code is a mish-mash of C-style programming and C++ iostreams programming. Why use fopen/fwrite/fclose? You should use std::ofstream and use the write member function, analogous to your readFile.read
.
Upvotes: 2