Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading in 4 bytes at a time

Tags:

c++

I have a big file full of integers that I'm loading in. I've just started using C++, and I'm trying out the filestream stuff. From everything I've read, it appears I can only read in bytes, So I've had to set up a char array, and then cast it as a int pointer.

Is there a way I can read in 4 bytes at a time, and eliminate the need for the char array?

const int HRSIZE = 129951336;  //The size of the table
char bhr[HRSIZE];   //The table
int *dwhr;

int main()
{
    ifstream fstr;

    /* load the handranks.dat file */
    std::cout << "Loading table.dat...\n";
    fstr.open("table.dat");
    fstr.read(bhr, HRSIZE);
    fstr.close();
    dwhr = (int *) bhr;    
}
like image 782
oadams Avatar asked Jun 04 '10 13:06

oadams


1 Answers

To read a single integer, pass in the address of the integer to the read function and ensure you only read sizeof int bytes.

int myint;

//...

fstr.read(reinterpret_cast<char*>(&myint), sizeof(int));

You may also need to open the file in binary mode

fstr.open("table.dat", std::ios::binary);
like image 106
Yacoby Avatar answered Sep 25 '22 11:09

Yacoby