read a int from a file wrote by java’s writeInt method in C++?

How would one go about doing this? Also, is there an easy way to do it? Using a lib like Boost or something?

Answer

The DataOutputStream which writes out the int writes out a 4 byte int, with the high bytes first. Read into char*, reinterpret and if you need to convert the byte order use ntohl.

ifstream is;
is.open ("test.txt", ios::binary );
char* pBuffer = new char[4];

is.read (pBuffer, 4);
is.close();

int* pInt = reinterpret_cast<int*>(pBuffer);
int myInt = ntohl(*pInt); // This is only required if you are on a little endian box
delete [] pBuffer;

Leave a Reply

Your email address will not be published. Required fields are marked *