Newbie: how to read and analyse a binary file?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Jon2003
Forum Newbie
Posts: 7
Joined: Tue Apr 29, 2003 7:44 pm

Newbie: how to read and analyse a binary file?

Post by Jon2003 »

I want to reuse my own database written in C++. A record in C++ like that:

CPerson {
CString name, addr; int age;
Save (CArchive &ar) { ar << name; ar << addr; ar << age; }
};

So far I have just learned how to read all data into string as the following code:

Code: Select all

$filename = "mydata.dat";
$fd = fopen ($filename, "rb");
$contents = fread ($fd, filesize ($filename));
fclose ($fd);
But I am stuck, don't know how to analyse the data to get datas of records (say, to print out all names and ages).

Please help, many thanks in advance.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

do you know how the different mfc-classes encode their data? I do not ;)

A single character of a string can be accessed via $var{ $pos }, e.g.

Code: Select all

$s = 'abcdefg';
for ($i=0; $i!=strlen($s); $i++)
	echo ord($s{$i}), "\n";
Jon2003
Forum Newbie
Posts: 7
Joined: Tue Apr 29, 2003 7:44 pm

Post by Jon2003 »

Excellent!!! It is enough for me now. Thank you very much :D

BTW, if anyone know a better method (more effective), please let me know. For example, to get an integer of 4 bytes from the string, I have to write a look-like crazy code:

Code: Select all

$n = ord($s&#123;0&#125;)+(ord($s&#123;1&#125;)<<8)+(ord($s&#123;2&#125;)<<16)+(ord($s&#123;3&#125;)<<24);
Many thanks.
Post Reply