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;
}
int?memblock.